#include <iostream>using namespace std;int main(){int a,n,i=1;int S=0,t=0;cout<<"Please enter the integer and the number: "<<endl;cin>>a>>n;while(i<=n){S=S+t;t=t+a;a=a*10;i++;}cout<<"The result is: "<<S<<endl;return 0;}俺的程序是這樣的,但是有問題哈,比如輸入1,4回車,結果是123,按題目來說應該是1234,求指導俺是菜鳥勿噴
2 回答

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
應該是循環出了問題,建議以后循環盡量使用for語言,for語句比while語句的功能更強大.
你的程序其實只要把S=s+t;和t=t+a;交換一下位置就行了
#include <iostream>
using namespace std;
int main()
{
int a,n,i=1;
int S=0,t=0;
cout<<"Please enter the integer and the number: "<<endl;
cin>>a>>n;
while(i<=n)
{
t=t+a;
S=S+t;
a=a*10;
i++;
}
cout<<"The result is: "<<S<<endl;
return 0;
}
下面是我自己稍微修改的程序,看起來簡潔一點
#include <iostream>
using namespace std;
int main()
{
int a,n,i,t;
int S=0;
cout<<"Please enter the integer and the number: "<<endl;
cin>>a>>n;
t=a;
for(i=0;i<n;i++)//或者寫成for(i=1;i<=n;i++)都是循環n次的意思
{
S=S+a;
a=a*10+t;
}
cout<<"The result is: "<<S<<endl;
return 0;
}
- 2 回答
- 0 關注
- 1355 瀏覽
添加回答
舉報
0/150
提交
取消