C++ 为什么我在所有情况下都能得到0%的回报?

C++ 为什么我在所有情况下都能得到0%的回报?,c++,C++,我在Code::Blocks上创建了这个测试分数程序,根据学生在测试中获得的最大可达分数和分数来计算学生测试的百分比,但在所有情况下,结果都是0%,我不知道为什么 有人能帮我解释一下吗 #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; int main(int nNumberofArgs, char* pszArgs[]) { //enter t

我在Code::Blocks上创建了这个测试分数程序,根据学生在测试中获得的最大可达分数和分数来计算学生测试的百分比,但在所有情况下,结果都是0%,我不知道为什么

有人能帮我解释一下吗

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

{
  //enter the maximum reachable score
  int maxscore;
  cout << "Enter the highest possible score: ";
  cin >> maxscore;

  //enter the reached score
  int score;
  cout << "Enter your score: ";
  cin >> score;

  //calculate percentage
  //what's wrong here with the percentage calculation?
  int percentage;
  percentage =  (score/maxscore)*100 ;

  //output the results (followed by a NewLine)
  cout << "Your result is: ";
  cout << percentage <<"%"<< endl;

  //wait until user is ready before terminating the program to allow the user 
  //to see the program results
  cout << "Pres Enter to continue..."<<endl;
  cin.ignore(10, '\n');
  cin.get();
  return 0;
}

您的问题是使用整数作为百分比。使用浮点数支持小数点。下面是一个带有浮点数的代码示例:

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

{
  //enter the maximum reachable score
  int maxscore;
  cout << "Enter the highest possible score: ";
  cin >> maxscore;

  //enter the reached score
  int score;
  cout << "Enter your score: ";
  cin >> score;

  //calculate percentage
  //what's wrong here with the percentage calculation?
  float percentage;
  percentage =  (score/maxscore)*100 ;

  //output the results (followed by a NewLine)
  cout << "Your result is: ";
  cout << (int) (percentage+0.5) <<"%"<< endl; // fast the Float to int for Zero decimal and add 0.5 befördert fast for rounding.

  //wait until user is ready before terminating the program to allow the user 
  //to see the program results
  cout << "Pres Enter to continue..."<<endl;
  cin.ignore(10, '\n');
  cin.get();
  return 0;
}
您应该更改:

percentage =  (score/maxscore)*100 ;
进入


因为score/maxscore被威胁为整数,因此被限定为0,当乘以100时,它只能是100的倍数。

关键字:整数算术,score/maxscore不会产生您想要的结果expecting@VTT那么它是如何工作的呢?通过将int-percentage更改为float-percentageTypo:float->float。我自己会改的,但是,如果您正在进行中间编辑,我不想挤压东西。无论如何,这个答案都是错误的,因为它仍然会使用相同的整数算术表达式计算百分比,并生成0.0f…提示:首先使用浮点分数。除非有人想要浮点百分比值,否则不需要在任何地方使用浮点值。@VTT如果您不想让这个东西移动,就没有必要了有一些惊人的舍入错误。
percentage = (score*100)/maxscore ;