我正在尝试编写一个c ++程序,它以int a-5项开头,每秒int b - 变大2倍。例如,1秒打印 - 5,2秒 - 10,3秒 - 20.然后打印它的总和。 (35)。因为我是一个非常初学者,所以坚持下去。
int main()
{
int a,b;
cout << " Enter a and b: " << endl;
cin >> a >> b;
for (int i=1; i<=b; i++) {
cout << i << endl;
}
return 0;
}
这在cin 3秒后打印1,2,3。我试着用+ = i求和,但我不知道它是如何工作的。如何编写一个告诉计数的代码 循环中n + nx2 + nx2x2 + nx2x2x2 ....
谢谢!
答案 0 :(得分:0)
您需要制作一个新变量result
。然后根据您的逻辑修改其值。
int result = 0;
for (int i=1; i<=b; i++) {
result = result + a;
cout << a << endl;
a = a * 2;
}
cout << result << endl;
答案 1 :(得分:0)
#include <iostream>
using namespace std;
int main()
{
int a,b,i,result;
cout << " Enter a and b: " << endl;
cin >> a >> b;
result = a; // At 0 sec result is a
for (i=1; i<=b; i++)
{
result = result*2; // Doubles the result at every second
cout <<result<< endl;
}
return 0;
}
答案 2 :(得分:-1)
现在你只是打印出它循环的次数,因为你从i=1
转到i=3
。因此,i
的{{1}}值为:{1}}时为1,2,3。那么这与算法有什么关系:
b = 3
你想出来了。找到该模式并使用您的a+at+at*t .... +n
值。