【问题标题】:C++ For loop Beginner incorrect outputC ++ For循环初学者不正确的输出
【发布时间】:2014-12-21 20:38:06
【问题描述】:

我今年开始上大学,学习的是软件开发课程。我刚刚开始在 C++ 中做循环,并被分配了许多要解决的问题。我已经完成了第一个问题的代码,但部分输出无法正常工作,我不知道为什么。

问题是在一次测试中读取 10 个学生的分数,然后输出获得荣誉分数的学生的百分比(超过 70)

这是我的代码

  int _tmain(int argc, _TCHAR* argv[])

{
    int grade;
    int numfirstclass = 0;
    int percentfirstclass;


    for (int count = 0; count < 10; count++)// For loop to run 10 times to allow 10 grades to be entered
    {
        cout << "Enter your grade ";
        cin >> grade;

        if (grade >= 70)
            numfirstclass++;
    }


    cout << "The number of students with a first class honours degree is:" <<  numfirstclass;
    percentfirstclass = (numfirstclass / 10) * 100;
    cout << endl << "The Percentage of students that recieved a first class degree is: " << percentfirstclass;



    return 0;
}

我的问题是 percentfirstclass 的输出总是 0,我不知道为什么。

任何解释将不胜感激

我正在使用 Visual Studio 2013

【问题讨论】:

  • numfirstclass/10 始终为 0,因为 numfirstclassint 的值 int 计算,请将其更改为 double,如果您还是有问题。
  • 您强制 C++ 首先评估 numfirstclass/10,对于低于 10 的每个数字(因为它们是整数),这将是 0。乘以 100 来得太晚了。删除括号并将100 放在开头。 ...或乘以 (100/10)。
  • 谢谢大家,我把它改成了双倍,现在可以工作了。对不起菜鸟的错误。我现在明白了

标签: c++ loops for-loop int


【解决方案1】:

使用

percentfirstclass = (numfirstclass / 10(double)) * 100;

numfirstclass / 10 将始终计算为 0(numfirstclass 为 1 时除外),因为它是整数除法,并且 100 和 0 相乘始终为 0。

使用强制转换将使 numfirstclass / 10(double) 产生一个具有小数部分的数字,然后将其乘以 100 。然后这个数字将分配给percentfirstclass,因为percentfirstclassint,小数部分将被截断。

【讨论】:

    【解决方案2】:

    问题在于子表达式

    (numfirstclass / 10)
    

    表达

    percentfirstclass = (numfirstclass / 10) * 100;
    

    总是等于 0,因为 numfirstclass 总是小于 10,除了 numfirstclass 等于 10 的情况。:) 使用整数运算。

    您可以将numfirstclass 定义为具有浮点(或双精度)类型或将语句重写为

    percentfirstclass = (numfirstclass * 100 ) / 10;
    

    或强制将表达式计算为浮点数

    percentfirstclass = (numfirstclass / 10.0) * 100;
    

    【讨论】:

      【解决方案3】:

      正如帅哥所说,将percentfirstclass 更改为float 或double,在上面的代码中,您试图将一个整数除以10,该整数小于10,因此程序返回0 作为输出 即

      int c =1; int d = c/10;//给出0,因为整数不支持小数

      如果你使用

      float d = c/10;//你会得到你需要的输出

      希望你明白了。

      【讨论】:

        【解决方案4】:

        只需输入类型double.Write

        double percentfirstclass;
        percentfirstclass = (numfirstclass / 10.0) * 100;
        

        改为

        int percentfirstclass;
        percentfirstclass = (numfirstclass / 10) * 100;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-05
          • 1970-01-01
          • 2016-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多