只返回第一个if语句? (C ++)

时间:2016-02-22 21:45:58

标签: c++ if-statement switch-statement

这是我正在进行的任务:

  

编写一个程序,提示用户输入课程所获得的分数并确定分数。该程序应显示成绩的成绩和消息字符串。使用'if else'语句来确定打印消息字符串的等级和switch语句。

我编写了代码并且执行时没有任何调试错误。问题是,无论我输入什么export https_proxy=https://user:pass@172.18.*.*:80 export http_proxy=http://user:pass@172.18.*.*:80 export ftp_proxy=ftp://user:pass@172.18.*.*:80 ,我只得到F的输出!例如,如果我输入“90”:

PointsEarned

有什么问题?我把我的switch语句放在错误的地方吗?这是代码:

Try Harder Next Time.
GRADE: F

5 个答案:

答案 0 :(得分:5)

比较形式0 <= PointsEarned < 60在Python中工作但不在C ++中工作。您应该使用0 <= PointsEarned && PointsEarned < 60

答案 1 :(得分:4)

您不能像以下那样测试多个值:

if (0 <= PointsEarned < 60) {

这不是检查PointsEarned0之间是否60。这些<中只有一个会被评估,这意味着您可以有效地测试某些东西

if (0 <= true/false) {

代替。

你需要更像

的东西
 if ((0 <= PointsEarned) && (PointsEarned < 60)) {

代替。

答案 2 :(得分:1)

if (0 <= PointsEarned < 60) { 正在打破C ++语言,改变它为2有效的比较 if (0 <= PointsEarned && PointsEarned < 60) {

答案 3 :(得分:0)

我重写了你的代码并做了一些改进:在其他行中如果(90 <= PointsEarned)我将它限制为100.还有其他评论者指出你不能测试多个值所以我重写了他们所说的。它现在工作正常!

#include <iostream>
using namespace std;
int main()
{
    int PointsEarned;
    char Grade;
    cout << "Please input the points earned in the course: ";
    cin >> PointsEarned;
    if ((0 <= PointsEarned) && (PointsEarned < 60)) {
        Grade = 'F';
    }
    else if ((60 <= PointsEarned) && (PointsEarned < 70)){
        Grade = 'D';
    }
    else if ((70 <= PointsEarned) && (PointsEarned < 80)) {
        Grade = 'C';
    }
    else if ((80 <= PointsEarned) && (PointsEarned < 90)){
        Grade = 'B';
    }
    else if ((90 <= PointsEarned) && (PointsEarned <= 100)) {
        Grade = 'A';
    }
    else{
        cout << "That is not a  valid input.";
    }
    switch (Grade)
    {
    case 'F':
    case 'D':
        cout << "Try Harder Next Time." << endl;
        break;
    case 'C':
        cout << "Good." << endl;
        break;
    case 'B':
        cout << "Very good." << endl;
        break;
    case 'A':
        cout << "Excellent." << endl;
        break;
    default:
        cout << "Please choose a valid input to receive your grade." << endl;
    }
    cout << "GRADE: " << Grade << endl;
}

答案 4 :(得分:0)

表达式:if (0 <= PointsEarned < 60)表示if ((0 <= PointsEarned) < 60)
表示if ((true/false) < 60)

上述表达式与您可能想要的表达式不同:
if ((0 <= PointsEarned) && (PointsEarned < 60))