习题5.2
#include<iostream>
using namespace std;
long intpower(int base,int exponent)
{
int BASE=base;
for(int i=1;i<exponent;i++)
base*=BASE;
return base;
}
int main()
{
int base,exponent;
int num;
cout<<"输入base=";
cin>>base;
cout<<"输入exponent=";
cin>>exponent;
num=intpower(base,exponent);
cout<<"base的exponent次幂="<<num<<endl;
return 0;
}
习题5.3
#include<iostream>
using namespace std;
int distinguish(int num)
{
int pn=0;
for(int i=2;i<=num-1;i++)
{
if(num%i==0)
pn++;
}
return pn;
}
int main() //prime number=pn
{
int num,pn;
cout<<"输入正整数:";//当然要除去1
cin>>num;
pn=distinguish(num);
if(pn==0)
cout<<"该数为质数"<<endl;
else
cout<<"该数不为质数"<<endl;
return 0;
}
习题5.4
#include<iostream>
using namespace std;
int antitone(int num)
{
int NUM;
NUM=num%10;
return NUM;
}
int main()
{
int num;
int ant_num;
cout<<"输入一串数字";
cin>>num;
cout<<endl<<"反序后为";
do
{
ant_num=antitone(num);
cout<<ant_num;
num=num/10;
}while(num%10);
cout<<endl;
return 0;
}
习题5.5
#include<iostream>
using namespace std;
int classify(int num)
{
char NUM;
if(num>=90)
NUM='A';
else if(num>=75&&num<90)
NUM='B';
else if(num>=60&&num<75)
NUM='C';
else
NUM='N';
return NUM;
}
int main()
{
int num;
char level;
cout<<"输入一百分制分数:";
cin>>num;
level=classify(num);
cout<<"分数等级:"<<level<<endl;
return 0;
}
习题5.6
#include<iostream>
using namespace std;
int MEAN(int a)
{
double sum=0;
for(int i=1;i<=10;i++)
{
cout<<"输入第"<<i<<"位学生成绩:";
cin>>a;
sum+=a;
}
sum=sum/10;
return sum;
}
int main()
{
int a;
double mean;
mean=MEAN(a);
cout<<"平均分:"<<mean<<endl;
return 0;
}
编程计算S[n]=1!+21+3!+...n!。要求定义两个函数,一个计算n!,一个计算s[n],在后一个函数中调用前一个函数。然后在主程序中输入数n的值,然后调用定义函数输出结果。
#include<iostream>
using namespace std;
int Nnn(int n)//计算n!
{
int j=1;
for(int i=1;i<=n;i++)
j=j*i;
return j;
}
int Sn(int n)//计算s[n]
{
int s=0;
for(int i=1;i<=n;i++)
s=s+Nnn(i);//用Nnn(i),不是用Nnn(n)
return s;
}
int main()
{
int n,s;
cout<<"输入n值吧"<<endl;
cin>>n;
s=Sn(n);
cout<<"s的输出为"<<s<<endl;
return 0;
}