【问题标题】:Why using if in this way is preventing it from running为什么以这种方式使用 if 会阻止它运行
【发布时间】:2021-12-20 01:22:27
【问题描述】:

所以这里的 if 循环内是否可以以优化的方式编写 if 语句,还是应该只拆分两个条件?

#include <iostream>
using namespace std;

int main()
{
    int grade, counter = 1, total = 0, average;

    while (counter <= 10)
    {
        cout << "Enter grade /100: ";
        cin >> grade;

        if (grade < 0 && grade > 100) //HERE PLEASE
        {
            cout << "invalid grade value." << endl;
            cout << "Reenter grade value */100*: ";
            cin >> grade;
        }
        
        total = total + grade;

        counter++;
    }
    
    average = total / 10;
    
    cout << "\nThe class average is:  " << average << endl;

    return 0;
}

【问题讨论】:

  • 不要将其标记为“c”,请先阅读您要应用的标记的 cmets!
  • your rubber duck 的一点帮助会有所帮助
  • 对 OP 的提示:您的程序正在测试 grade 是否为负数以及 grade 是否大于 100。同时为负数和大于 100 的值相对较少.

标签: c++ visual-studio if-statement visual-c++


【解决方案1】:
if (grade < 0 && grade > 100)

没有小于1的数字大于100,所以条件每次都会返回false

如果你想小于1大于100,试试:

if (grade < 0 || grade > 100)

总的来说,你的代码应该是:

#include <iostream>
// using namespace std; is bad practice, so don't use it

int main()
{
    int grade = 0, counter = 1, total = 0, average = 0;

    while (counter <= 10)
    {
        std::cout << "Enter grade /100: ";
        std::cin >> grade;

        if (grade < 0 || grade > 100) 
        {
            // use newline character instead of std::endl
            std::cout << "invalid grade value." << '\n'; 
            std::cout << "Reenter grade value */100*: ";
            std::cin >> grade;
        }
        // a = a + b is equal to a += b
        total += grade;

        ++counter;
    }
    
    average = total / 10;
    
    std::cout << "\nThe class average is:  " << average << '\n'; 

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2014-08-28
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多