main() {
float n1, n2, n3, n4, n5, agg_mrk, prcnt;
printf("Enter the marks of five students ");
scanf("%f, %f, %f, %f, %f", &n1, &n2, &n3, &n4, &n5);
printf("the five number entered by u is %f, %f, %f,%f, %f", n1, n2, n3, n4, n5);
agg_mrk = n1 n2 n3 n4 n5;
prcnt = agg_mrk / 5;
printf("The aggregate marks is %lf and the percentage is %f", agg_mrk, prcnt);
}
The first number is getting right value but all other numbers (n2
, n3
, n4
, n5
) showing garbage value:
CodePudding user response:
The input 67 78 90 56 78
does not match the expected syntax:
scanf("%f, %f, %f, %f, %f", &n1, &n2, &n3, &n4, &n5);
scanf()
skips any leading white space, then expects a float value, then expects a ,
, then ignores whitespace, then expects another float value, etc.
The input 67 78 90 56 78
does not have a comma after the first number so scanf()
stops converting and returns 1
, the number of successful conversions.
The values of n2
, n3
, n4
and n5
are unchanged, hence stay uninitialized, appearing as random values.
Note also that main
must be defined with a return type of int
.
Here is a modified version:
#include <stdio.h>
int main() {
float n1, n2, n3, n4, n5, agg_mrk, prcnt;
printf("Enter the marks of five students: ");
if (scanf("%f %f %f %f %f", &n1, &n2, &n3, &n4, &n5) != 5) {
printf("invalid input\n");
} else {
printf("the five number entered by u is %f, %f, %f,%f, %f\n",
n1, n2, n3, n4, n5);
agg_mrk = n1 n2 n3 n4 n5;
prcnt = agg_mrk / 5;
printf("The aggregate marks is %f and the percentage is %f\n",
agg_mrk, prcnt);
}
return 0;
}
CodePudding user response:
Try using this instead in 4th line:
scanf("%f %f %f %f %f", &n1, &n2, &n3, &n4, &n5);
So you can clearly see, when you put "," after %input, it expects a variable or a memory to store it into. Don't confuse scanf with printf, below code will work correctly with commas too.
printf("%f, %f, %f, %f, %f", n1, n2, n3, n4, n5);
I hope that you are able to spot the difference now.