英文:
I need to count averege but the answer is 1735473548 or something like that
问题
#include <stdio.h>
int main(void)
{
int total = 0;
int counter = 1;
int grade;
float average;
while(counter <= 10)
{
printf("Enter grade: ");
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
}
average = (float)total / 10;
printf("average is: %f", average);
}
我尝试计算10个数字的平均值。我做错了什么?
英文:
#include <stdio.h>
int main(void)
{
total = 0;
counter = 1;
while(counter <= 10)
{
printf("%s", "Enter grade: ");
scanf("%d", &grade);
total = total + grade;
counter = counter + 1;
}
average = total / 10;
printf("%d", "average is:", average);
}
I tried to calculate the average of 10 numbers. What am I doing wrong?
答案1
得分: 5
printf("%d", "average is:", average);
告诉 printf
接受一个 int
类型的参数,并将其作为十进制数打印出来,但是 "average is:"
将字符串的地址传递给了它,而不是一个 int
类型的参数。你应该使用 printf("The average is %d.\n", average);
。
启用警告并将其提升为错误进行编译。使用 Clang,从 -Wmost -Werror
开始。使用 GCC,从 -Wall -Werror
开始。使用 MSVC,从 /W3 /WX
开始。
一旦你让它正常工作,考虑将 average
和 total
改为 double
类型,而不是 int
类型。然后你需要将 %d
更改为另一种格式。
英文:
printf("%d", "average is:", average);
tells printf
to take an int
and print it as a decimal numeral, but "average is:"
passes it the address of the string instead of an int
. You should use printf("The average is %d.\n", average);
.
Compile with warnings enabled and elevated to errors. With Clang, start with -Wmost -Werror
. With GCC, start with -Wall -Werror
. With MSVC, start with /W3 /WX
.
Once you get that working, consider making average
and total
double
instead of int
. Then you will need to change %d
to another format.
答案2
得分: 0
在进行数学运算时,必须声明double或使用除法的float类型,以获得最准确的结果。如果不需要得到结果的小数部分,可以不声明。
在这种情况下,进行除法运算时,必须先将int类型转换为float类型,或者将其强制转换为float类型,结果才会正确。结果不总是单个数字结果的平均值。
这是一个必须知道的规则。
a = b / (c * 1.0)
或者:
a = (float)b / c 或者 a = (b * 1.0)/c
或者不进行任何操作,如果所有变量都声明为float或double类型。
double total = 0.0;
int counter = 1;
while(counter <= 10)
{
printf("Enter grade: ");
scanf("%lf", &grade);
total = total + grade;
counter = counter + 1;
}
double average = total / 10;
printf("average is: %lf", average);
英文:
Required when doing math, you must declare double, or float with division. For the most accurate results. If you don't need to get the float point of the result, you don't need to.
In this case, the division operation, you must convert the int type to float type first.
or cast to a float number, the result will be correct.
It's not always the average of a single digit result.
It's a must-know rule.
a = b / (c * 1.0)
or:
a = (float)b / c or a = (b * 1.0)/c
or do nothing, if all variables are declared as float, or double.
double total = 0.0;
int counter = 1;
while(counter <= 10)
{
printf("Enter grade: ");
scanf("%lf", &grade);
total = total + grade;
counter = counter + 1;
}
double average = total / 10;
printf("average is: %lf", average);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论