现在的位置: 首页 > 综合 > 正文

C++练习题(1)

2013年12月27日 ⁄ 综合 ⁄ 共 1149字 ⁄ 字号 评论关闭

1.1 编写程序练习int型,double型,char型数据以及字符串的输入和输出。

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int a;
double b;
char c;
char str[20];
cin>>a>>b>>c>>str;
cout<<"a:"<<a<<endl<<"b:"<<b<<endl<<"c:"<<c<<endl<<"str:"<<str<<endl;
return 0;
}

1.2  根据下面的函数原型编写函数,要求在函数中根据n的值,输出n是奇数或者是偶数。void f(int n);

#include<iostream>
using namespace std;
void f(int n)
{
if(n%2==0)
{
cout<<n<<"为偶数"<<endl;
}
else
{
cout<<n<<"为基数"<<endl;
}
}
int main()
{
f(3);
return 0;
}

1.3  根据下面的函数原型编写函数,要求在函数中读取一个字符,然后判断输入的字符是数字、或是大写字母、或是小写字母、或是其它的字符,并且以文字的形式将判断结      果输 出。void f();

#include<iostream>
using namespace std;
void f()
{
char c;
cout<<"请输入一个字符:";
cin>>c;
if(c>='0'&&c<='9')
{
cout<<c<<"为数字"<<endl;
}
else if(c>='A'&&c<='Z')
{
cout<<c<<"为大写字母"<<endl;
}
else if(c>='a'&&c<='z')
{
cout<<c<<"为小写字母"<<endl;
}
else
{
cout<<c<<"为其他字符"<<endl;
}
}
int main()
{
while(1)
{
f();
}
return 0;
}

1.4输入一个字符串,判断其为一个数还是一个字符串,用中文显示结果,该功能在void f()中完成。

【判断一个字符串是不是一个数的方法,单独依次判断每一个字符是不是>='0'&&<='9'】

#include<iostream>
using namespace std;
void f()
{
char c[20];
cout<<"请输入一个字符串:";
cin>>c;
int len = strlen(c);
int flag = 0;
int i = 0;
for(;i<len;i++)
{
if(!(c[i]>='0'&&c[i]<='9'))
{
flag = 1;
break;
}
}
if(flag==0)
{
cout<<c<<"为一个数"<<endl;
}
else
{
cout<<c<<"为一个字符串"<<endl;
}
}
int main()
{
while(1)
{
f();
}
return 0;
}

抱歉!评论已关闭.