帮忙解释一下这个程序 C++

来源:百度知道 编辑:UC知道 时间:2024/06/25 15:43:29
#include<iostream>
using namespace std;
int fun()

static int i=0;
int s=1;
s+=i;
i++;
return s;

int main()

int i,a=0;
for(i=0;i<5;i++)
a+=fun();
cout<<a<<endl;
return 0;


请帮忙解释一下这个程序 每一个字母和符号代表的意思 以及程序的内容 谢谢

#include<iostream> //使用包含标准流类库的头文件
using namespace std; //使用C++的标准名空间

int fun()//声明一个函数fun

static int i=0;//定义一个静态的整型数i,并初始化为0
int s=1; //定义一个整型数s,并赋值为1
s+=i; //把当前i的值加在s上
i++; //即i=i+1,i增加1
return s; //返回s,就是调用fun()时fun()的值为s
}
int main()//主函数
{
int i,a=0;//定义整型数i,a,用0初始化a
for(i=0;i<5;i++) //让下面的循环体执行5次
a+=fun(); //每次执行时把fun()值加在a上.注意循环体就这一句
cout<<a<<endl; //在屏幕上显示最后a的值
return 0; //返回一个0给main(),这是因为用的是标准代码(头两行)
}

这个函数运行时,从主函数开始,运行到“a+=fun();”时第一次调用fun(),执行语句“s+=i;”s值为1+0=1,i++变成了1,返回fun()的值为s即1.“a+=fun();”的执行结果a=0+1=1,再执行第二次循环,调用fun()s得2,i得2,返回fun()为2,加在a上得3……直到第五次循环结束,a=1+2+3+4+5=15.在屏幕上输出15,返回0并程序结束

补充一点,二楼回答有误,using namespace std; 并不多余。如果写的是
#include<iostream.h>就不用说明名空间std,但是这里用的是<iostream>是C的写法,C++下应该添上std。

#include<iostream>
using namespace std; //这个是多余的,等同于#include<iostream>
i