In my C Program, I want to get the average of the sum of numbers being entered until the program stops. What should I add to check the average? Thank you!
#include <stdio.h>
int main (void)
{
int x;
int sum = 0;
int average;
int testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF !=EOF)
sum +=x;
} while (testEOF !=EOF);
printf ("\nTotal: %d\n", sum);
printf ("\nAverage: %d\n", average);
return 0;
//main
}
As other people explained, you have to initialize sum and count, they are never given their initial values. No need to initialize average and x because you assign sum/count to average and users will assign any value to x.
You have to put everything you want your if statement to do in {...}. But you didn't. Your if statement only does sum +=x and does not work for count++ and average = sum / count. So your program increases the value of count even after EOF. So you found 14/6 rather than 14/5.
You checked testEOF != EOF twice. One is in the if statement, other is in do-while.
I put the code below:
#include <stdio.h>
int main (void){
float x;
float sum = 0;
float count = 0;
float average;
float testEOF;
printf("Enter your numbers: <EOF> to stop.\n");
while(1){
testEOF = scanf("%f", &x);
if (testEOF ==EOF){
break;
}
sum +=x;
count++;
average = sum / count;
}
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
#include <stdio.h>
int main (void)
{
float x;
float sum;
float count;
float average;
float testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%f", &x);
if (testEOF !=EOF)
sum +=x;
count++;
average = sum / count;
} while (testEOF !=EOF);
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
This is now almost correct. The only thing is that the number is not getting divided by the number of values entered.
Example:
2
3
3
3
3
Sum is 14
Average: 2.3 (should be 2.8)
This seems that count is being added by 1 every time I get the average.
Well if you want your output to be printed with decimal point you can do the following , in that case
for inputs like 0, 1, 1 the out would be 0.666667 otherwise it will be simply 0 ignoring the decimal part.
the while part can be optimized as suggested by #David C. Rankin
double sum = 0;
double average = 0;
unsigned int count = 0;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF != EOF)
{
sum += x;
count++;
}
} while (testEOF != EOF);
printf ("\nTotal: %f\n", sum);
average = sum / count;
printf ("\nAverage: %f\n", average);
Related
program wherein there shouldn't be negatives in the equation and it will end when 0 as input
#include <stdio.h>
int main() {
double number, sum = 0;
int average;
int count;
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
if (number > 0)
sum += number;
average = sum / (count);
} while (number != 0);
printf("Average is %.1lf", average);
return 0;
}
In your program you are counting all numbers independent on whether they are positive or negative
do {
printf("Enter a number: ");
scanf("%lf", &number);
count++;
//...
Also it does not make a sense to calculate the average within the do while loop.
average = sum / (count - 1);
And it is unclear why the variable average has the type float instead of double.
float average;
And you forgot to initialize the variable count.
Pay attention to that the user can enter neither positive number.
And as it follows from the title of your question you are going to enter integer numbers not double.
The program can look the following way
#include <stdio.h>
int main( void )
{
double sum = 0.0;
double average = 0.0;
size_t count = 0;
while( 1 )
{
printf( "Enter a number: " );
int number;
if ( scanf( "%d", &number ) != 1 || number == 0 ) break;
if ( number > 0 )
{
sum += number;
++count;
}
}
if ( count != 0 ) average = sum / count;
printf( "Average is %f\n", average );
return 0;
}
Firstly, you didn't initialize your count variable. That said, you should increment the count variable only when a non negative value is encountered. Unrelated but I'd recommend you calculate the average outside the loop, as below:
#include <stdio.h>
int main()
{
double number, sum = 0;
float average;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &number);
if (number > 0)
{
sum += number;
count++;
}
} while (number != 0); //should it stop with 0 or 1? assuming 0
average = sum / count;
printf("Average is %.1lf\n", average);
return 0;
}
First of all, always enable your compiler's warnings. I use -Wall -Wextra -pedantic with gcc and clang. This would have caught the first of the problems listed below if nothing else.
There are many problems.
count is not initialized.
Negative numbers aren't included in the sum as you claim, but they do affect the average because you increment count for negative numbers too.
The assignment asks for you to loop until you get zero, but you loop until you get -1.
The formula for average isn't sum / (count - 1).
average is calculated over and over again for no reason.
You don't handle the case where no inputs are entered, leading to a division by zero.
average is a float, which is odd since you it's built from double values.
You should check the value returned by scanf for errors or end of file.
You don't emit a line feed after your output.
#include <stdio.h>
int main(void) {
int count = 0.0;
double sum = 0.0;
while (1) {
printf("Enter a number: ");
double number;
if ( scanf("%lf", &number) < 1 ) // Invalid input or EOF.
break;
if ( number == 0.0 )
break;
if ( number < 0.0 )
continue;
count++;
sum += number;
}
if (count) {
double average = sum / count;
printf("Average is %.1lf\n", average);
} else {
printf("Nothng to average\n");
}
return 0;
}
I'm new at this and having some trouble. I'm trying to find the average of the grades that are inputed by the user but I realized that if you use a decimal in any of the grades, it's just being calculated as if they are whole numbers.
#include <stdio.h>
int main(void)
{
unsigned int counter;
float grade;
int total;
float average;
int number;
total = 0;
counter = 1;
printf("Number of scores to enter:\t");
scanf("%d", &number);
printf("\n");
while (counter <= number) {
printf("%s%d%s", "Enter the score for Lab ", counter, ":\t");
scanf("%f", &grade);
total = total + grade;
counter = counter + 1;
}
printf("\n");
average = (float) total / number;
printf("Average lab score: %.1f\n", average);
if (grade>=90) {
puts("Letter grade: A");
}
else if (grade>=80) {
puts("Letter grade: B");
}
else if (grade>=70) {
puts("Letter grade: C");
}
else if (grade>=60) {
puts("Letter grade: D");
}
else {
puts("Letter grade: F");
}
return 0;
}
You are capturing scanf("%f", &grade); as a float and then calculating total = total + grade;.
You have defined int total;. You would need to define it as float total;.
You are moving a float variable into an integer which is truncating the decimals you had previously entered.
There's no need to ask up front how many data points will be entered. Indeed, that is an anti-pattern. Just do something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
printf("Average lab score: %.1f\n", average);
fputs("Letter grade: ", stdout);
putchar( average >= 90.0 ? 'A' : average >= 80.0 ? 'B' :
average >= 70.0 ? 'C' : average >= 60.0 ? 'D' : 'F');
putchar('\n');
return average >= 60.0;
}
$ echo 78.2 96.5 80 | ./a.out
Average lab score: 84.9
Letter grade: B
Key points: total needs to be a float type. You must check the value returned by scanf. Always. Probably you want to handle bad input more cleanly that this does. This just throws away all data after an error and computes the average based on whatever data was entered prior to the error. A cleaner solution would abort with an error message. Exercise left for the reader.
A reasonable argument can be made that this is an abuse of the ternary operator; however you want to refactor it, don't repeat yourself by hardcoding the string "Letter grade: " multiple times.
Rather than abusing the ternary operator as above, you may prefer something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
int s = 'A' + (99 - (int)average) / 10;
printf("Average lab score: %.1f\n", average);
printf("Letter grade: %c\n", s > 'D' ? 'F' : s);
return average >= 60.0;
}
disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.
I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}
So i'm writing a statistical calculator program, and the first function I started to write was the mean calculator. My issue is that I'm getting extremely large( and wrong) values for the answers.
Please Enter a number of inputs
4
Please enter number 1
1
Please enter number 2
2
Please enter number 3
3
Please enter number 4
4
Statistical Calculator Menu
(1) Mean
(2) Standard Deviation
(3) Range
(4) Restart/Exit
1
3940705125981218000000000000000000.000000
Here is my source code.
const int MAX_DATA=5;
void menu(float numbers[], int amount);
float mean(float numbers[],int amount);
int main()
{
int i, amount;
float numbers[MAX_DATA];
printf("Please Enter a number of inputs \n");
scanf("%d", &amount);
if (amount>MAX_DATA){
printf("You entered too many numbers");
}else{
for (i=1;i<amount+1;i++){
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
menu(numbers,amount);
}
getch();
return 0;
}
void menu(float numbers[],int amount)
{
int input2;
printf("Statistical Calculator Menu");
printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit");
scanf("%d",&input2);
if(input2==1){
mean(numbers,amount);
}
}
float mean(float numbers[],int amount)
{
int i;
float sum;
float average;
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
average=sum/amount;
printf("%f", average);
return average;
}
Can someone point out the mistake, or explain why this isn't calculating correctly?
You are not initialising sum so it is taking whatever garbage value was last in that place on the stack. Change:
float sum;
To:
float sum = 0;
Another problem you have is:
for(i = 1; i < amount + 1; i++) {
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
Array indexes start at 0, so this should be:
for(i = 0; i < amount; i++) {
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
Apart from what Mike said,
for (i=1;i<amount+1;i++)
{
printf("Please enter number %d\n", i);
scanf("%f",&numbers[i]);
}
float mean(float numbers[],int amount)
{
// ..
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
....
From this, you are not filling numbers[0]. But in the mean calculation, using the value at 0 index.
float sum;
float average;
for (i=0; i<amount;i++){
sum=sum+numbers[i];
}
sum is not initialized in your program.