一、项目1:利用循环求和
for语句
#include<iostream>
using namespace std;
int main()
{
int x,sum;
cout<<"请计算出1000以内所有偶数之和:"<<endl;
for(x=1,sum=0;x<=1000;x++)
{
if(x%2==0)
sum=sum+x;
else
sum=sum+0;
}
cout<<sum<<endl;
return 0;
}
do-while语句
#include<iostream>
using namespace std;
int main()
{
int x(0),sum(0);
do
{
x=x+2;
sum=sum+x;
}while(x<=998);
cout<<"sum="<<sum<<endl;
}
while语句
#include<iostream>
using namespace std;
int main()
{
int x(0),sum(0);
while(x<=1000)
{
sum=sum+x;
x=x+2;
}
cout<<"sum="<<sum<<endl;
}
二、项目6:输出星号图
#include <iostream>
using namespace std;
void main( )
{
int a,b;
for(a=1;a<=6;a++)
{
for(b=1; b<=6-a; b++)
cout<<" ";
for(b=1; b<=2*a-1; b++)
cout<<"*";
cout<<endl;
}
for(a=1;a<=5;a++)
{
for(b=1; b<=a; b++)
cout<<" ";
for(b=1; b<=2*(6-a)-1; b++)
cout<<"*";
cout<<endl;
}
}
三、项目二:贪财的富翁
#include <iostream>
using namespace std;
int main()
{
double i=0.01,sum1=0,sum2=0,d=1;
for(d=1; d<=30; ++d)
{
sum1=sum1+i;
sum2=sum2+100000;
cout<<"第"<<d<<"天:陌生人给了百万富翁"<<100000<<"元\n";
cout<<"第"<<d<<"天:百万富翁给了陌生人"<<i<<"元"<<endl;
i=2*i;
}
cout<<"一个月中陌生人给了百万富翁"<<sum2<<"元\n";
cout<<"一个月中百万富翁给了陌生人"<<sum1<<"元"<<endl;
cout<<"富翁亏了"<<endl;
return 0;
}