This is the original problem : ""A class of ten students took a quiz. The grades for this
quiz are available to you. Determine the class average on the quiz""
int main(){
float average, total, currentnote, i;
average,total = 0;
for (i = 0; i < 10; i++){
printf("please enter the quiz result:");
scanf_s("%d", ¤tnote);
total = total + currentnote;
if (i = 9){
average = total / 10;
printf("result equals= %f", average);
getchar();
}
}
}
After I enter one number it exits with error
The program '[3272] Project1.exe' has exited with code 0 (0x0).
Can someone show me my error?
Besides having to test for equality as if (i == 9),
you can't set two variables equal to a common value this way: average, total = 0
Do average = total = 0 instead.
The currentnote variable is a float - but your format flag for scanf_s is telling it to expect an int.
For clarity of intention in the code, why is this inside the for loop? Why not put it after the for loop?
if (i == 9){
average = total / 10;
printf("result equals= %f", average);
getchar();
}
if (i = 9)
Should be
if (i == 9)
See if that's the problem.
You wrote:
scanf_s("%d"....
But %d is for ints, and you have a float.
Use %f.
Related
Hello I have a small problem with my code and I want to understand it. My task is to write a program that take the sum and average for n numbers with while loops or nested while loops with if conditions, when you want to exit the code you should enter -1. The code is down below. The problem I have is that I can't get it to exclude the -1 from the calculation. What am I doing wrong. And it is suppose to be a simple code.
int main(void) {
int count;
float sum, average, number;
sum = 0;
count = 0;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
scanf("%f", &number);
sum = sum + number;
count = count + 1;
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
in the while block, you read the number and then add it to your average calculation, and only then after the iteration repeats you're checking if it's different than -1 to stop the iteration:
there are obviously different ways to solve it:
one way can be to use while(true) and in the while block after you read the number add an if statement to compare it with -1 and break out of the loop
while (true) {
scanf("%f", &number);
if (number == -1) break;
sum = sum + number;
count = count + 1;
}
Reordering the different steps could solve this:
int main(void) {
int count;
float sum, average, number=0.0f;
sum = 0;
count = -1;
printf("Calculate sum and average (-1 to quit)\n");
while (number!=-1) {
sum = sum + number; // first time no effect with 0
count = count + 1; // first time "no effect" counting to 0
scanf("%f", &number); // will not be counted or summed if -1
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Think it through with immediatly entered -1:
sum is 0+0, suitable for no numbers being added up
count is -1+1==0, suitable for no numbers
dividing by 0 should be avoided, but that is a separate issue
Think it through with one number:
number is read in with sum==0 and count==0
is not -1, so loop iterates again
sum and count are updated meaningfully
-1 one is entered
loop ends without processing -1
By the way, comparing a float for identity is risky. You would be safer if you could compare more "generously", e.g. while (number>-0.5).
I think you should take the input at the last of the loop as it will get check in the next iteration. And when -1 comes up it will not be added.
#include <stdio.h>
int main(){
int count=0;
float sum=0, average=0, number=0;
printf("Calculate sum and average (-1 to quit)\n");
while(number!=-1){
sum = sum + number;
count = count + 1;
scanf("%f", &number);
}
average = sum / count;
printf("Sum=%f", sum);
printf(" Average=%f", average);
}
Code needs to test number as -1 before including it in the summation. OP's code test almost does this right. OP's code test for -1 before number is even assigned leading to undefined behavior (UB).
float number;
while (number!=-1) { // UB!
Also good to test the return code of scanf() for success.
while (scanf("%f", &number) == 1 && number != -1) {
sum = sum + number;
count = count + 1;
}
I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!
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 am really stuck with this been trying to solve it for quite a time now.
i have to write a program where i should input 5 numbers between 1 to 10 and then calculate the average, USING ONLY WHILE LOOP, but it does not have to exit when the number does not meet the requirement. then, i have to write a variation of the same code but this time you can enter all the numbers you want, and when 0 is entered it has to calculate the average and exit
this is where i have gotten so far
#include <stdio.h>
int main(void)
{
int n, i = 1;
float add;
float avg;
do
{
printf("enter the number %d:\n", i++);
scanf("%d", &n);
add = add + n;
} while(n > 0 && n < 11);
avg= (add / 5);
printf("%.1f", avg);
return 0;
}
it will keep asking for numbers after 5 have been entered. and the average is not right anyways
First, you're using nas your while condition variable, but also as the variable to scan the input. If I start your program by scanning 20, for example, your while loop will exit on the first interaction. Use your i variable instead and also increment it every time your loop executes.
do{
...
}while(i <= 5);
Second, if you want only numbers between 1 and 10, then you should write a condition for it. For example:
printf("enter the number %d:\n", i); //do not increment it here!
scanf("%d",&n); //assuming "n" as your variable to scan
if(n > 0 && n < 11){
add += n;
i++; //increment it here instead!
}
Third, initialize your variables in order to not get thrash values
float add = 0;
float avg = 0;
int i = 1;
Finally, assign your result (not mandatory, but since you're using it I'll keep it):
avg = add/5.0f
and display:
printf("%.1f", avg);
I am working on a change counter program and I am stuck, I have searched here and 2 other coding forums, google and youtube, but haven't found an answer yet...my program sucks and i am brand new to c/c++...my txt book is not here yet so I am trying to read every every thing i can get my hands on till it gets here
This is what the output should be in the console window:
Welcome to Change Counter by Jo Mama!!
Please enter the total amount of purchase: $52.173
$52.173
Please enter amount of money tendered: $60
$60.00
Your change is: $7.83
-------------------------------------------
Twenties : 0
Tens : 0
Fives : 1
Ones : 2
Quarters : 3
Dimes : 0
Nickels : 1
Pennies : 3
-------------------------------------------
Thank you for using Change Counter!
here is what i have so far...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
// define variables here
long double numberOfTwenties = 0;
long double numberOfTens = 0;
long double numberOfFives = 0;
long double numberOfOnes = 0;
long double numberOfQuarters = 0;
long double numberOfDimes = 0;
long double numberOfNickels = 0;
long double numberOfPennies = 0;
double purchasePrice = 0;
double amountTendered = 0;
double amountOfChange = 0;
double amountOfChangeCents = 0;
// start program here
printf("Welcome to the change counter by Josh Manion!!\n\n");
printf("Please enter the total amount of purchase: $");
scanf("%d", &purchasePrice);
printf("%d\n", purchasePrice);
printf("Please enter amount of money tendered: $");
scanf("%d", &amountTendered);
printf("%d\n", amountTendered);
//do change calculations here
amountOfChange = (amountTendered - purchasePrice);
printf("Your change is: $%d\n", amountOfChange);
numberOfTwenties = amountOfChange / 20;
//amountOfChange = numberOfTwenties %= amountOfChange;
numberOfTens = (amountOfChange / 10);
numberOfFives = (amountOfChange / 5);
numberOfOnes = (amountOfChange / 1);
numberOfQuarters = (amountOfChange * 0.25);
// print change calculations here
printf("---------------------------------------------\n");
//display denominations of change here
printf("Twenties: %d\n", numberOfTwenties);
printf("Tens: %d\n", numberOfTens);
printf("Fives: %d\n", numberOfFives);
printf("Ones: %d\n", numberOfOnes);
printf("Quarters: %d\n", numberOfQuarters);
printf("Dimes: %d\n", numberOfDimes);
printf("Nickels: %d\n", numberOfNickels);
printf("Pennies: %d\n", numberOfPennies);
printf("---------------------------------------------\n");
printf("Thank you for using the Change Counter!");
getchar();
return EXIT_SUCCESS;
}
The problem is that my program doesn't work, it shows the change after the prompt but not the breakdown of denominations, I am sposed to use the "%" to bring down the change amount, but i havent found any examples. I don't know what else to say... besides I'm new and this post will help a lot of people...
Your program has undefined behaviour : you must use %Lf as the printf modifier to print a long double (same issue with your usage of scanf)