c++ - C++ 初学者 "while"程序

标签 c++

我必须解决一个问题,我计算员工的薪水,他们在前 40 小时每小时获得 10 欧元,然后每增加一个小时他们获得 15 欧元。我已经解决了问题,但我的控制台无限循环地打印答案,我不知道我哪里错了。

int hours;
double salary;

int main()
{

    cout << "Enter amount of hours worked" << endl;
    cin >> hours;

    while (hours <= 40)
    {
        salary = hours * 10;
        cout << "Salary of the employee is: " << salary << endl;
    }

    while (hours > 40)
    {
        salary = (40 * 10) + (hours - 40) * 15;
        cout << "Salary of the employee is: " << salary << endl;
    }

    system("pause");
    return 0;
}

最佳答案

while 更改为 if

while 中的条件将始终为 true,因为 hours 将始终小于 40,因为没有修改 hours while 条件内,因此导致无限循环

修改后的代码:

int hours;
double salary;

int main()
{

    cout << "Enter amount of hours worked" << endl;
    cin >> hours;

    if (hours <= 40)
    {
        salary = hours * 10;
        cout << "Salary of the employee is: " << salary << endl;
    }
    else //I have removed the condition because if hours is not less than 40,
        // it has to be greater than 40!
    {
        salary = (40 * 10) + (hours - 40) * 15;
        cout << "Salary of the employee is: " << salary << endl;
    }

    system("pause");
    return 0;
}

使用 while 循环的解决方案。

既然你一心想得到一个 while 循环解决方案,

代码:

int hours;
int counthour = 0;
double salary;

int main()
{

    cout << "Enter amount of hours worked" << endl;
    cin >> hours;

    while (counthour <= hours)
    {
        if(counthour <= 40)
            salary += 10;
        else
            salary += 15;
        counthour++;

    }
    cout << "Salary of the employee is: " << salary << endl;
    system("pause");
    return 0;
}

关于c++ - C++ 初学者 "while"程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546092/

相关文章:

Android 应用程序因 C++ 中的字符串操作而崩溃

c++ - curl.h 没有这样的文件或目录

c++ - 一个好的重新分区算法

c++ - 多次登录时检测多个应用实例的变化

c++ - 在 C++ 中使用 Windows API 播放音频流

c++ - 如何在执行 LoadLibrary ("*.exe"时初始化 CRT)

c++ - memcpy是将float打包到uint32中的标准方法吗?

c++ - 使用 MFC 对象初始化 std::map 不编译

c++ - 无需运行必备软件的 DirectX 游戏

c++ - 我正在尝试用 C++ 做一个方程式,但它一直输出 1