I have the following code in c
#include <stdio.h>
int main(void)
{
int a, b, c, sum;
double d, p;
sum = a b c;
printf("请输入三个整数:");
scanf("%d %d %d", &a, &b, &c);
d = sum / 3;
printf("3个整数的平均值是:d=%.2f", d);
p = a / sum * 100;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
}
It is about entering three integers from the keyboard, average them, and calculate the ratio of the first number to the sum of the three numbers. The output result retains 2 decimal places . I cannot find where is wrong.
CodePudding user response:
The two main issues are:
- You calculate
sum
with uninitialized values fora
,b
andc
. Move that calculation to after a successfulscanf()
to ensure those variables are set. - You probably want to do the calculations of
d
andp
with double, rather than integer, precision. I make use of automatic type conversion via fractional constants. The other two options are to change the type ofsum
from anint
to adouble
, or explicitly use a type cast (see answer by @FeihuLiu).
Minor issues:
- Original code was formatted poorly (since fixed by one of our friends :-).
- Optional for
main()
but it's a good idea toreturn
an integer as your declaration said you would. - (not fixed) If you don't use
p
ord
for anything else, consider just eliminating them in favor of doing the calculation call toprintf()
- It's generally a good idea to reduce the scope of variables so I moved those definitions to just before they are used.
#include <stdio.h>
int main(void) {
printf("请输入三个整数:");
int a, b, c;
if (scanf("%d %d %d", &a, &b, &c) != 3) {
// TBD: translate error message
printf("scanf failed\n");
return 1;
}
int sum = a b c;
double d = sum / 3.0;
printf("3个整数的平均值是:d=%.2f", );
double p = 100.0 * a / sum;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
return 0;
}
CodePudding user response:
Besides the sum
problem, integer division will result in integer. You can use the following code:
#include <stdio.h>
int main(void) {
int a, b, c, sum;
double d, p;
printf("请输入三个整数:");
scanf("%d %d %d", &a, &b, &c);
sum = a b c;
d = (double) sum / 3;
printf("3个整数的平均值是:d=%.2f", d);
p = (double) a / sum * 100;
printf(",第一个数占和的比例是:p=%4.2f%%", p);
}