计算用户输入数字的平均值

时间:2015-10-28 22:29:36

标签: c user-input

在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%”。

为什么会这样?

2 个答案:

答案 0 :(得分:1)

主要问题在于:

printf("Your average score is %d%%", &averageScore );

您正在使用期望%d的{​​{1}}格式说明符。您要打印的值为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

答案 1 :(得分:0)

请试试这个,它有效。

#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 );
}