我无法弄清楚如何重复此程序,因此用户可以输入另一组小时。
我是否需要将此更改为" Do ... While"声明?
我正在考虑添加一个"用户定义的函数"最后,但我的教授可能不允许这样,因为我们还没有到达那里。
#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;
}
答案 0 :(得分:0)
建议将工作分解为命名良好的函数,然后根据用户如何终止循环来建立循环逻辑。
答案 1 :(得分: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
}