在C:中使用此代码
int main() {
double score1;
double score2;
double averageScore;
printf("Please enter your score in course1.");
scanf("%lf", &course1_score);
printf("Please enter your score in course2.");
scanf("%lf", &course1_score);
averageScore = (score1 + score2)/2;
printf("Your average score is %d%%", &averageScore );
return 0;
}
无论我输入什么数字,输出都会不断给我:"你的平均分数是1606416176%"。
为什么会发生这种情况?
主要问题在这里:
printf("Your average score is %d%%", &averageScore );
您使用的是%d
格式说明符,它需要一个int
。您要打印的值是double
,因此需要%f
格式说明符。此外,您应该传入averageScore
,而不是&averageScore
。
您得到的值是averageScore
变量的地址,被解释为int
。由于该地址在每次运行时都是相同的(但不一定),因此您会看到相同的值。
所以这行应该是:
printf("Your average score is %f%%", averageScore );
此外,似乎还有一个拼写错误:
printf("Please enter your score in course1.");
scanf("%lf", &course1_score);
printf("Please enter your score in course2.");
scanf("%lf", &course1_score);
也许你指的是score1
和score2
?
请尝试一下,它有效。
#include <stdio.h>
int main( )
{
double score1 = 0;
double score2 = 0;
double averageScore = 0;
double total = 0;
printf( "Please enter your score in course 1.n" );
scanf( " %lf", &score1 );
printf( "Please enter your score in course 2.n" );
scanf( " %lf", &score2 );
total = score1 + score2;
printf( " Total score = %5.2lf n", total );
averageScore = ( score1 + score2 ) / 2;
printf( "Your average score is %5.2lf", averageScore );
getchar( );
return ( 0 );
}