473,398 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

averaging numbers in text file

I'm trying to add numbers from a text file and find the average. The
numbers in the file are:

25 50 75 100

I expect the result to be 62.50 but I get 85.00. I've twiddled with
the condition expression of the for statement but apparently I have no
idea what I'm doing. Post-increment or pre-increment seems to make no
difference. Any help appreciated.

/* avg.c : find the average of n integers
in a text file */
#include <stdio.h>

int main() {
int num, i;
float sum;

for(i = 0; i != '\n'; i++)
{
scanf("%d", &num);
sum += num;
}
printf("The average is %.2f\n", sum/i);
return 0;
}

Thanks,
Bill
Nov 13 '05 #1
9 5199
Bill Reed wrote:
I'm trying to add numbers from a text file and find the average. The
numbers in the file are:

25 50 75 100

I expect the result to be 62.50 but I get 85.00. I've twiddled with
the condition expression of the for statement but apparently I have no
idea what I'm doing. Post-increment or pre-increment seems to make no
difference. Any help appreciated.

/* avg.c : find the average of n integers
in a text file */
#include <stdio.h>

int main() {
int num, i;
float sum;

for(i = 0; i != '\n'; i++)
{
scanf("%d", &num);
sum += num;
}
printf("The average is %.2f\n", sum/i);
return 0;
}

Assuming an architecture with ASCII character set, we have '\n' == 10.
Thus, for i going from 0 to 3, you scan the four numbers in your file,
so that sum equals 250. For the next 6 attempts, the scanf execution
fails to interpret anything, and, I suppose, num is unchanged, so that
you actually add 6 * 100 = 600 to your sum.

At the end of the for loop, we thus have sum == 850. So that your
average is 850 / 10 = 85.

That i != '\n' *has* to be a huge brainfart, 'cause else, you are hereby
sentenced to not write a line of C code until you have read, re-read and
re-re-read the K&R 2 !

That said, please note that:
1) you really want to use doubles instead of floats. The possible gain
in program footprint is far outweigh by the loss in precision when you
prefer to use floats.
2) for regular counters (happilly hopping from 0 to some arbitrary N),
you should prefer to use the size_t type.
3) only Dan Pop has enough clues to use scanf directly. The rest of us
prefer to use fgets or variants thereof (I _do_ like ggets), with
possibly sscanf or strto*.
4) in your printf, sum/i actually had type float, while your printf
conversion specifier (%f) expects a double.

--
Bertrand Mollinier Toublet
"Uno no se muere cuando debe, sino cuando puede"
- Cor. Aureliano Buendia

Nov 13 '05 #2
Bill Reed wrote:
On Tue, 22 Jul 2003 20:46:00 -0700, Bertrand Mollinier Toublet
<be***********************@enst-bretagne.fr> wrote:
Assuming an architecture with ASCII character set, we have '\n' == 10.
Thus, for i going from 0 to 3, you scan the four numbers in your file,
so that sum equals 250. For the next 6 attempts, the scanf execution
fails to interpret anything, and, I suppose, num is unchanged, so that
you actually add 6 * 100 = 600 to your sum.

At the end of the for loop, we thus have sum == 850. So that your
average is 850 / 10 = 85.

Although, please note that this is a probable explanation, but nothing
you can rely on. Remember that when you have undefined behaviour in your
program (sun being uninitialized, which I missed, is an example),
*anything* can happen, and it generally doesn't bring much to try and
explain what happened.

The typical example of "Don't explain" is anything along the lines of

i = i++ + ++i;

You can spend hours saying "the good result should be this or that
because this or that", but it is all moot: the expression invokes
undefined behaviour, is illegal, and is allowed to yield any result it
wants including letting DEMONs (those missile-mounted nuclear warheads)
fly out of the local NOSE (the operating center to launch the warheads).

--
Bertrand Mollinier Toublet
"No sea vivo, Buendia" -- El presidente del tribunal,
in Cien anos de soledad, de Gabriel Garcia Marquez

Nov 13 '05 #3
On Wed, 23 Jul 2003 03:13:26 GMT, Bill Reed <ag***@wi.rr.com> wrote:
I'm trying to add numbers from a text file and find the average. The
numbers in the file are:

25 50 75 100

I expect the result to be 62.50 but I get 85.00.


with scanf would be fine use switch + goto

#include <stdio.h>

int main()
{int num=0, i, c;
float sum=0;/* here num=0, sum=0 */

printf("Inserisci i numeri: "); fflush(stdout);
for(i=0;;)
{switch(scanf("%d[^\n]", &num))
{case 1: sum += num;
++i;
if((c=getchar())==EOF || c=='\n')
goto label;
else ungetc(c, stdin);
break;
case 0:/*if scanf meets one letter (a,b,c..) or EOF end*/
case EOF: goto label;
}
}
label:
printf("The average is %.2f\n", (float) (sum/i) );
return 0;
}

Nov 13 '05 #4
#include <stdio.h>

int main()
{int num=0, i, c;
float sum=0;/* here num=0, sum=0 */

printf("Inserisci i numeri: "); fflush(stdout);
for(i=0;;)
{switch(scanf("%d[^\n]", &num))
{case 1: sum += num;
++i;
if((c=getchar())==EOF || c=='\n')
goto label;
else ungetc(c, stdin);
break;
case 0:/*if scanf meets one letter (a,b,c..) or EOF end*/
case EOF: goto label;
}
}
label: i==0?++i: 0; printf("The average is %.2f\n", (float) (sum/i) );
return 0;
}


Nov 13 '05 #5
On Wed, 23 Jul 2003 09:11:49 -0700, "Mike Wahler"
<mk******@mkwahler.net> wrote:
So far I have this but I need to do more reading.

/* avg.c : find the average of n integers
in a text file */
#include <stdio.h>

int main() {
int num, i;
double sum = 0;
FILE *fptr1;
char file1[] = "avg.txt";
fptr1 = fopen(file1, "r");
YOu need to check that the file was opened successfully.
If 'fopen()' returned NULL, it was not, and you should
not try to read from the file.


By 'opened successfully' do you mean that the file exits? When I use
the command:

avg < avg.txt

if avg.txt does not exist the system lets me know. Or are there other
problems I might encounter?

for(i = 0; !feof(fptr1); i++)


You're using feof() incorrectly. It doesn't indicate
end of file until *after* an attempt to read *past*
end of file.
{
scanf("%d", &num);
sum += num;
}
printf("The average is %.2f\n", sum/i);
return 0;
}

It compiles with no errors or warnings but doesn't do anything.


Actually, it does. It waits for *you* to do something.
'scanf()' takes input from 'standard input', which is
typically a 'console' on systems that have one. If you
want to read from a file, use 'fscanf()' or 'fgets()'
or 'fgetc()' etc.

BTW which book(s) are you reading? Perhaps you need
better one(s).


I looked up feof() in "Teach Yourself C in 24 Hours". I purchased K&R
2 yesterday. The former books description of the function seems
comparable to K&R 2 but his program examples don't appear to lend
themselves to my application. Probably I just need to read and think
about it some more.

Bill
Nov 13 '05 #6
On Thu, 24 Jul 2003 05:56:25 GMT, gi******@giuseppe.wwwew (Giuseppe)
wrote:
On Wed, 23 Jul 2003 03:13:26 GMT, Bill Reed <ag***@wi.rr.com> wrote:
I'm trying to add numbers from a text file and find the average. The
numbers in the file are:

25 50 75 100

I expect the result to be 62.50 but I get 85.00.


with scanf would be fine use switch + goto

#include <stdio.h>

int main()
{int num=0, i, c;
float sum=0;/* here num=0, sum=0 */

printf("Inserisci i numeri: "); fflush(stdout);
for(i=0;;)
{switch(scanf("%d[^\n]", &num))
{case 1: sum += num;
++i;
if((c=getchar())==EOF || c=='\n')
goto label;
else ungetc(c, stdin);
break;
case 0:/*if scanf meets one letter (a,b,c..) or EOF end*/
case EOF: goto label;
}
}
label:
printf("The average is %.2f\n", (float) (sum/i) );
return 0;
}


This is interesting. If I remove the printf() and fflush() line the
result is exactly what I was looking for. As mentioned in another post
I should probably declare sum as a double so it doesn't need to be
converted later. This is very different from anything I was
considering as a solution. Thanks.

Bill

Nov 13 '05 #7
Bill Reed wrote:
if avg.txt does not exist the system lets me know. Or are there other
problems I might encounter?
Bill...

On my system fopen() can fail even when the file exists if I
don't have the requisite file permission(s).
Probably I just need to read and think about it some more.


(A winning strategy! 8^)
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #8
On Thu, 24 Jul 2003 11:10:57 -0500, Bill Reed <ag***@wi.rr.com> wrote:
On Thu, 24 Jul 2003 05:56:25 GMT, gi******@giuseppe.wwwew (Giuseppe)
wrote:
On Wed, 23 Jul 2003 03:13:26 GMT, Bill Reed <ag***@wi.rr.com> wrote:
I'm trying to add numbers from a text file and find the average. The
numbers in the file are:

25 50 75 100

I expect the result to be 62.50 but I get 85.00.


with scanf would be fine use switch + goto

#include <stdio.h>

int main()
{int num=0, i, c;
float sum=0;/* here num=0, sum=0 */

printf("Inserisci i numeri: "); fflush(stdout);
for(i=0;;)
{switch(scanf("%d[^\n]", &num))
{case 1: sum += num;
++i;
if((c=getchar())==EOF || c=='\n')
goto label;
else ungetc(c, stdin);
break;
case 0:/*if scanf meets one letter (a,b,c..) or EOF end*/
case EOF: goto label;
}
}
label:
printf("The average is %.2f\n", (float) (sum/i) );
return 0;
}


This is interesting. If I remove the printf() and fflush() line the
result is exactly what I was looking for. As mentioned in another post
I should probably declare sum as a double so it doesn't need to be
converted later. This is very different from anything I was
considering as a solution. Thanks.

Bill

please you note that if there is not input => case 0 => i=0 => sum/i
ERROR
Nov 13 '05 #9
On Thu, 24 Jul gi******@giuseppe.wwwew (Giuseppe) wrote:
#include <stdio.h>

int main()
{int num=0, i, c;
float sum=0;/* here num=0, sum=0 */

printf("Inserisci i numeri: "); fflush(stdout);
for(i=0;;)
{switch(scanf("%d[^\n]", &num))
{case 1: sum += num;
++i;
if((c=getchar())==EOF || c=='\n')
goto label;
else ungetc(c, stdin);
break;
case 0:/*if scanf meets one letter (a,b,c..) or EOF end*/
case EOF: goto label;
}
}
label:

i==0?++i: 0;
printf("The average is %.2f\n", (float) (sum/i) ); printf("The average is %.2f\n", (double) (sum/i) );
^^^^^^^^
Why for scanf %f is float and for printf %f is double?
return 0;
}


Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: pj | last post by:
Why does M$ Query Analyzer display all numbers as positive, no matter whether they are truly positive or negative ? I am having to cast each column to varchar to find out if there are any...
1
by: Rotten Spice | last post by:
Hello all, I am still pretty new to Access but I do have a grasp on some basic functions. I am having a problem with averaging and I think I'm trying to do something a little too complex and...
27
by: Mark A. Nicolosi | last post by:
I've been trying to learn C for quite a while. But I've had trouble with the lack of good quality online text (some of it's alright). But I finally bought a book on C, Practical C. I like it...
3
by: Millennium Falcon | last post by:
Hi! Help is kindly requested in reading floating point numbers from a text file. File is organized like this : 2000 // number of data -1.00000 -2.000000 -0.008944 // x, y & z-coordinates to...
8
by: microsoft.news.com | last post by:
I have a text file that has a column of numbers that i need to add to get a total of. Is there any way to add the number column in my text file? the text file looks like this: BMW ...
2
by: shihaoran | last post by:
I really need help with one my program; it is about arraylist; I do not get it. Can someone please help me with it? Here's the instruction: 1. Your instructor will provide you with a text...
1
by: JJ R | last post by:
I am trying to develop a simple and efficient to calculate averages. For example I want to calculate the averages of the Values for rows 1 and 2 and use ID 1 as the row with the average result. ...
0
by: troy_lee | last post by:
I have a report based on a query. It is a simple listing of returned merchandise that has been repaired and shipped. I have a text box in the detail section that calculates the total days the...
1
by: Kid Programmer | last post by:
Hello guys. Whenever I am learning a new programming language I like to learn the basics (variables, loops, conditionals etc) by writing a program that will calculate averages. I wrote a simple...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.