实验一 实验环境与简单程序设计(C++)
一、实验目的
- 了解和使用VC集成开发环境,掌握C++程序的基本要素以及完整的C++程序开发过程。
- 掌握基本数据类型、运算符和表达式的使用。理解隐式转换和强制转换,理解数据超过该数据类型表示范围时的溢出。掌握不同数据之间的混合算术运算中数据类型的转换。
- 变量的定义与常量的使用。
- 输入、输出的实现。
- 编译信息的理解与错误的修改。
- 简单程序的设计。
二、实验内容与解答
1、熟悉Visual C++实验环境
2、启动VC,建立一个控制台应用程序,在显示器上输出:
***********************
Hello,C++!
I am xx班 xxx。
************************
解答:
#include<iostream>
using namespace std;
int main ()
{
cout<<"***********************\n"<<endl;
cout<<"Hello,C++!"<<endl;
cout<<"I am xx班 xxx。"<<endl;
cout<<"\n***********************\n"<<endl;
return 0;
}
3、编辑输入下列程序,找出下面代码的错误并改正:
include<iostream>
using namespace std;
int Main()
{
int i=k+1;
cout<<i++<< endl;
int i=1;
cout<<i++<< endl;
cout<<”Welcome to C++!<<endl;
return 0
}
解答:
修改后程序:
#include<iostream>
using namespace std;
int main ()
{
int k = 1;
cout<<++k<<endl;
int i = 1;
cout<<i++<<endl;
cout<<"Welcome to c ++"<<endl;
return 0;
}
4、求圆锥的体积:要求键盘输入圆锥底的半径、锥高,使用标识符常量定义圆周率。
#include<iostream>
using namespace std;
const double PI = 3.14159;
int main()
{
double r;
double h;
double v;
cout<<"Please enter 圆锥的底面半径 r = ";
cin>>r;
cout<<"Please enter 圆锥的高 h = ";
cin>>h;
v = PI * r * r * h / 3;
cout<<"圆锥的体积v = "<<v<<endl;
return 0;
}
5、通过下面程序验证你所使用系统上运行的C++编译器中每个基本数据类型的长度。
#include <iostream>
using namespace std;
int main()
{
cout << "char length:" << sizeof( char ) << endl;
cout << "int length:" << sizeof( int ) << endl;
return 0;
}
修改程序,验证short,long,float,double,long double,wchar_t的类型长度。
#include<iostream>
using namespace std;
int main()
{
cout<<" char length ; "<<sizeof(char)<<endl;
cout<<" int length ; "<<sizeof(int)<<endl;
cout<<" short length ; "<<sizeof(short)<<endl;
cout<<" long length ; "<<sizeof(long)<<endl;
cout<<" double length ; "<<sizeof(double)<<endl;
cout<<" float length ; "<<sizeof(float)<<endl;
cout<<" long double length ; "<<sizeof(long double)<<endl;
cout<<" wchar_t length ; "<<sizeof(wchar_t)<<endl;
return 0;
}
6、观察下面程序的执行结果。
#include <iostream>
using namespace std;
int main()
{
unsigned int testUnint=65535;//0xffff
cout << "output in char type:" << static_cast<char>(testUnint)<< endl;
cout<<"output in short type:" << static_cast<short>(testUnint)<<endl;
cout << "output in int type:" << static_cast<int> (testUnint)<< endl;
cout<<"output in double type:" << static_cast<double>(testUnint)<< endl;
system(“pause”);
return 0;
}
自己编程测试一下将一个实数转换成int,观察结果。
#include <iostream>
using namespace std;
int main()
{
unsigned int testUnint=65535;//0xffff
cout << "output in char type:" << static_cast<char>(testUnint)<< endl;
cout<<"output in short type:" << static_cast<short>(testUnint)<<endl;
cout << "output in int type:" << static_cast<int> (testUnint)<< endl;
cout<<"output in double type:" << static_cast<double>(testUnint)<< endl;
return 0;
}