#include <iostream>
using namespace std;
int main()
{
int r, g, b, y, rf, gf, bf;
cout << "Insert three numbers stating values of red, green, and blue fish respectively at initial state:" << endl;
cin >> r >> g >> b;
while (r<=0 || b<=0 || g<=0) {
cout << "Input invalid. All values must be above 0. Please reenter:" << endl;
cin >> r >> b >> g;
}
cout << "Please enter how many years have passed since initial state:" << endl;
cin>> y;
while (y<=0) {
cout << "Input invalid. Year must be 1 or higher. Please reenter:" << endl;
cin >> y;
}
for (int i=0; i<=y; i++) {
rf = r + r * .10 - 100;
gf = g + g * .15 - 100;
bf = b + b * .05 - 100;
}
if (rf<0) {
rf=0;
}
if (gf<0) {
gf=0;
}
if (bf<0){
bf=0;
}
cout << "After "<< y << " years there are:" << endl<< rf << " Red fish" << endl << gf << " Green fish" << endl << bf << " Blue fish" << endl;
return 0;
}
在这里向comp sci学生介绍。我正在研究我的术语项目,并在这个“for”循环中执行选定的表达式一定次数(y)。但是当我编译和执行时,无论我为y做什么,我都会得到相同的结果。我在这里做错了什么?
答案 0 :(得分:2)
你没有累积rf
他们将始终以相同的方式计算,y次
答案 1 :(得分:2)
如果你想做我认为你做的事,这应该有效。您每次都对rf,gf和bf执行相同的计算,因为无论您进行多少次计算,r + r * .10 - 100都会相同,因为r的值不会改变。 / p>
编辑:同样,对于rf,gf和bf,您需要浮点值,因为您乘以百分比。将它们初始化为0。 (如果它仍然无效,请尝试将它们全部浮动)
for (int i=0; i<=y; i++)
{
rf = rf + r * .10 - 100;
gf = gf + g * .15 - 100;
bf = bf + b * .05 - 100;
}
或
for (int i=0; i<=y; i++)
{
rf += r * .10 - 100;
gf += g * .15 - 100;
bf += b * .05 - 100;
}
答案 2 :(得分:2)
我猜for循环是错误的,请检查下面的正确答案:
for (int i=0; i<=y; i++)
{
rf += r + r * .10 - 100;
gf += g + g * .15 - 100;
bf += b + b * .05 - 100;
}
您必须使用+ =运算符
更新rf,gf和bf