如何在 C++ 中重复 "for" 循环

How to repeat a "for" loop in C++

我不知道如何重复这个程序,所以用户可以输入另一组时间。

我需要将其更改为 "Do...While" 语句吗?

我正在考虑在最后添加一个 "User-defined function",但我的教授可能不允许这样做,因为我们还没有做到这一点。

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const float initialVolume = 130.00;
const float decreaseRate = 0.13;
string name;
int counter = 0;

int main()
{
    int hours,i,j,k;
    float remainingVolume, halfVolume, zeroVolume;

    cout << "Enter hours to see how much caffeine "
         << "is left in your body, after you drank your coffee: ";
    cin >> hours;
    cout << endl;
    cout << fixed << showpoint << setprecision(4);

    remainingVolume = initialVolume;

    for (i = 0; i < hours; i++)
    {
        counter++;
        remainingVolume = remainingVolume - decreaseRate * remainingVolume;
        cout << "Hour " << setw(5) << counter << setw(15) << remainingVolume << "mg"<< endl;
    }

    for (j = 0, halfVolume = 130.00; halfVolume > 65.0000; j++)
    {
        counter++;
        halfVolume = halfVolume - decreaseRate * halfVolume;
    }

    for (k = 0, zeroVolume = 130.00; zeroVolume > 0.0001; k++)
    {
        counter++;
        zeroVolume = zeroVolume - decreaseRate * zeroVolume;
    }

    cout << "\n" << endl;
    cout << "It will take " << j << " hours to get caffeine levels to 65mg. \n" << endl;
    cout << "It will take " << k << " hours to get caffeine levels to 0mg." << endl;

    return 0;
}

我建议将工作分解为命名良好的函数,然后将循环逻辑基于用户将如何终止循环。

一种简单的方法,如果读取错误(例如,用户键入非整数值或按下 ^D(Linux/UNIX)或 ^Z(Windows) 生成文件结束条件:

int main()
{
    int hours,i,j,k;
    float remainingVolume, halfVolume, zeroVolume;

    while (cout << "Enter hours to see how much caffeine "
                << "is left in your body, after you drank your coffee: " &&
           cin >> hours)
    {
        cout << endl;
        cout << fixed << showpoint << setprecision(4);
        ...etc...
    }
    // no need to return 0; - that's done implicitly
}