c++ 用函数求1到100 的和

c++ 用函数求1到100 的和


摇曳的蔷薇
浏览 1224回答 1
1回答

皈依舞

#include&nbsp;"iostream.h"//引入头文件int&nbsp;Sum(int&nbsp;a,int&nbsp;b);//函数声明int&nbsp;main(){&nbsp; &nbsp; int&nbsp;a,b,sum=0;&nbsp; &nbsp; cout<<"请输入起始整数:"<<endl;&nbsp; &nbsp; cin>>a;&nbsp; &nbsp; cout<<"请输入终止整数:"<<endl;&nbsp; &nbsp; cin>>b;&nbsp; &nbsp; sum=Sum(a,b);//调用Sum函数&nbsp; &nbsp; cout<<sum<<endl;&nbsp; &nbsp; return&nbsp;0;}int&nbsp;Sum(int&nbsp;a,int&nbsp;b)//函数定义,实现求从a到b的和{&nbsp; &nbsp; int&nbsp;i,sum=0;&nbsp; &nbsp; for&nbsp;(i=a;i<=b;i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; sum+=i;//或者写成:sum=sum+i;&nbsp; &nbsp; }&nbsp; &nbsp; return&nbsp;sum;}若求从1到100的和,则起始整数输入为1,终止整数输入为100。以上程序运行结果为:
打开App,查看更多内容
随时随地看视频慕课网APP