大一上C++编程练习题
- 格式:docx
- 大小:16.49 KB
- 文档页数:3
一、熟悉2010开发环境
using namespace std;
#include<iostream>
void main()
{
intn,i;
cin>>n;
for(i=2;i<n;i++)
{
if(n%i==0)
{
break;
}
}
if(n==i)
{
cout<<"是素数。
"<<endl;
}
else
{
cout<<"不是素数。
"<<endl;
}
}
2.输入年份,判断是否是闰年。
(练习)
二、复习函数的定义、调用和声明using namespace std;
#include<iostream>
boolIsPrime(int n);
void main()
{
int m;
cin>>m;
if(IsPrime(m))
{
cout<<"是素数。
";
}
else
{
cout<<"不是素数。
";
}
}
boolIsPrime(int n)
{
inti;
for(i=2;i<n;i++)
{
if(n%i==0)
{
break;
}
}
if(n==i)
{
return true;
}
else
{
return false;
}
}
////
函数的定义包括四部分:1.返回值类型;2.函数名;3.形参列表;4.函数体函数有三种形式:函数的定义,函数声明,函数的调用。
三、类的定义
using namespace std;
#include<iostream>
//类是用户自定义的一种数据类型。
class Date //类的定义
{
private: //类中成员的访问权限
intyear,month,day; //类中的数据成员
public:
voidSetDate(inty,intm,int d);
voidIsLeap();
void Output();
}; //类的结束,一定有分号
void Date::SetDate(inty,intm,int d)
{
year=y;month=m;day=d;
}
void Date::IsLeap()
{
if(year%400==0 || (year%4==0&&year%100!=0))
{
cout<<"是闰年。
"<<endl;
}
else
{
cout<<"不是闰年。
"<<endl;
}
}
void Date::Output()
{
cout<<year<<"年"<<month<<"月"<<day<<"日"<<endl; }
void main()
{
Date dd;
dd.SetDate(2008,12,4);
dd.Output();
dd.IsLeap();
}。