为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 1242 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信