练习1
使用cout实现输出斐波那契前20项的值
#include <iostream>
using namespace std;
int fun1(int n )
{
int sum;
if (n==1)
{
sum =1;
}
else if(n==2)
{
sum =2;
}
else{
sum= fun1(n-1)+fun1(n-2);
}
return sum;
}
int main()
{
int n = 20;
int i = 1;
while(i<=n)
{
cout << "fifo's " <<i<<" is "<<fun1(i)<< endl;
i++;
}
return 0;
}
练习2
使用cin和cout完成,提示并输入一个字符,判断该字符是大写还是小写,如果是大写字母,则转变成对应的小写字母输出,如果是小写字母,则转变成对应的大写字母输出,如果是其他字符,则转变成 '*' 并输出
#include <iostream>
using namespace std;
int main()
{
char ch = '\0';
while(1){
cout<<"input ch:";
cin>>ch;
if(ch>='A'&&ch<='Z')//大写转小写
{
ch+=32;
}
else if(ch>='a'&&ch<='z')//小写转大写
{
ch-=32;
}
else{
ch ='*';
}
cout<<ch<<endl;
}
return 0;
}
练习3
提示并输入一个字符串,统计该字符串中字母、数字、空格、其他字符的个数并输出
#include <iostream>
using namespace std;
int main()
{
string s1;
cout<<"input s1:";
getline(cin,s1);
int al=0;
int dig=0;
int space=0;
int other=0;
int i = 0;
int n = s1.size();
while(i<n)
{
if(s1[i]>='0' && s1[i]<='9')
{
al++;
}
else if(s1[i]>='A' && s1[i]<='z')
{
dig++;
}else if(s1[i]==' ')
{
space++;
}
else
other++;
i++;
}
cout<<"al = "<<al<<"dig = "<<dig<<"space = "<<space<<"other = "<<other<<endl;
return 0;
}