亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C++里求S=a+aa+aaa...你懂得

C++里求S=a+aa+aaa...你懂得

C++
繁花不似錦 2018-07-29 14:14:39
#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;
}

查看完整回答
反對 回復 2018-08-01
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

把i初始化為0

追問

弱弱問下是i=1的時候就不是從1開始加的嗎?原理是啥哩

追答

自己一步步的試一下就知道了,第一循環的時候S = S+t 等于什么都沒加
所以第二次循環的時候才加第一個數
所以需要n+1次循環


查看完整回答
反對 回復 2018-08-01
  • 2 回答
  • 0 關注
  • 1355 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號