Why am I getting the wrong average in C? - c

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;
}

Related

c program regarding loops

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;
}

Average of Numbers in a Loop

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);

Printing the average of combined student marks using C

I've made this program below to calculate the average mark of a student.
Everything works well until I use -1, it is supposed to stop the program as is display the average of all students that have been entered, say Goodbye! and then terminate.
I think my calculations might be wrong though because it is printing the wrong result for the average marks of the students.
Thanks in Advance.
#include <stdio.h>
int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
for (i = 0; i < 2; i++)
{
printf("Enter assignment 1 mark (-1 to quit): ");
scanf("%d", &a_mark1);
if(a_mark1 == -1)
{
average_mark += final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
if ((average_mark > 1 ) && (average_mark < 100 ))
{
printf("The average student mark is %.2f%% \n", average_mark);
}
printf("Goodbye! \n");
return 0;
}
printf("Enter assignment 2 mark: ");
scanf("%d", &a_mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab_mark);
printf("Enter quiz mark: ");
scanf("%d", &quiz_mark);
printf("Enter exam mark: ");
scanf("%d", &exam_mark);
printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
}
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}
I think you need to rethink your logic a little bit. Why not use a while loop to control the flow. Then you can bail out of the program immediately if user inputs -1 right away. You should use an array to store the averages for each student, then you can loop through and find the class average as well.
-Your float final_mark function seems a little sketchy without any parenthesis.
-You should put your function prototype outside of main as well. See below changes.
#include <stdio.h>
#define MAX_STUDENTS 10 //define what the max number of students is
float final_mark(int mark1, int mark2, int lab, int quiz, int exam);
int main()
{
int i = 0, mark1 = 0, mark2 = 0,
lab = 0, quiz = 0, exam = 0;
int num_students;
float students_avg[MAX_STUDENTS] = {0}; //array to hold averages for students
float average = 0;
while (i < MAX_STUDENTS) {
printf("Enter assignment 1 mark (enter -1 to quit):\n");
scanf("%d", &mark1);
if (mark1 == -1)
break; //no more students, break out of while loop
printf("Enter assignment 2 mark: ");
scanf("%d", &mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab);
printf("Enter quiz mark: ");
scanf("%d", &quiz);
printf("Enter exam mark: ");
scanf("%d", &exam);
average = final_mark(mark1, mark2, lab, quiz, exam);
students_avg[i] = average; //add this average to array
printf("Student # %d average was %.2f\n", i, students_avg[i]);//debug info
i++;
}
num_students = i; //how many students grades did we read?
average = 0; //reset to 0 so we can use below
for (i = 0; i < num_students; i++)
average += students_avg[i];
if (num_students > 0)
printf("Class average is %.2f\n", average/num_students);
else
printf("Goodbye!\n");
return 0;
}
float final_mark(int mark1, int mark2, int lab, int quiz, int exam)
{
//we can just return the calculation
return ((mark1 * 0.1) + (mark2 * 0.15) + (lab * 0.15) + (quiz * 0.1) + (exam * 0.5));
}
Just erase two lines above printf("GOODBYE! \n"); you will get what you want.
maybe you have to initialized mark s variables to 0. and a_mark1 to 0 too if the user enter -1

Cash Register Program - C

Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}

How can I find the average of a single grade, and then of multiple grades in C?

I am trying to make a program that will take ask for the grade recieved, the total on the assignment, then average this. They keep doing this till they want to stop, at which point they will input -1. I cannot get it to average correctly, it is always coming out as 0.00, I'm new to C so I am sure it is a simple oversight, Thank you for any help you can offer.
#include <stdio.h>
#include <conio.h>
int main( void )
{
unsigned int counter;
int grade;
int total;
int asavg;
int asavgv;
float average;
total = 0;
counter = 0;
printf("%s", "Enter grade, -1 to end: " );
scanf("%d", &grade );
printf("Enter total possible: ");
scanf("%d", &asavg );
asavgv = grade / asavg;
while ( grade !=-1) {
total = total + asavgv;
counter = counter + 1;
printf ("%s", "Enter grade -1 to end: ");
scanf("%d" , &grade);
printf("Enter total possible: ");
scanf("%d", &asavg );
asavgv = grade / asavg;
}
if ( counter != 0 ) {
average = ( float ) total / counter;
printf("Average is %.2f\n", average );
}
else {
puts("no grades were entered");
}
getch();
}
Change
int asavgv;
to
double asavgv;
and then do
asavgv = grade*1.0 / asavg;
or
asavgv = (double)grade / asavg;

Resources