为什么在这个程序中我在所有情况下都得到0%?

时间:2017-07-29 19:05:34

标签: c++

我已经在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;
}

2 个答案:

答案 0 :(得分:1)

你应该改变:

percentage =  (score/maxscore)*100 ;

percentage = (score*100)/maxscore ;

因为score/maxscore被威胁为整数,所以&#34; floor()ed&#34;为0,当乘以100时,它只能是100的倍数。

答案 1 :(得分:-2)

您的问题是使用整数作为百分比。使用Float进行小数位数支持。以下是使用Float的代码示例:

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