题目1 最简单的C++程序
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello,this is ccx's first program!"<<endl;
return 0;
}
1.若将main改为Main将编译错误,可见C++区分大小写
实验2 阅读并编译、运行程序
#include <iostream>
using namespace std;
int main()
{
int iv1,iv2;
char cv1,cv2;
cout<<" iv1 = "<< iv1 <<" iv2 ="<< iv2 <<endl;
cout<<" size of iv1: "<< sizeof(iv1) <<endl;
cout<<" size of cv1: "<< sizeof(cv1) <<endl;
cout<<"please enter two number:";
cin>>iv1>>iv2;
cv1=++iv1; //80的ASCII码是P
cv2 = iv2++;
cout << " cv1 = " << cv1 << ", cv2 =" << cv2 <<endl; //输出了Q和P 因此++的运算符
cv2=125;
cout << cv2 <<endl;
return 0;
}
输入数据:80 80 得 Q P }
97 97 得 b a }
870 870得 g f }
1.若将#include <iostream>用#include<iostream.h>代替并删除第2 行语句using namespace std;
答:Code::Blocks 下不可行。
#include<iostream.h>是C语言风格,C标准里不用#include<iostream.h>
而用#include<iostream>
VC6是在C标准之前发布的,所以可用#include<iostream.h>形式
而VS2010 采用标准C格式
注:C标准 :ANSI(American National Standards Institute)C:有四个:C89 C90 C99 C11
若在C语言下运行该程序:
结果仍相同
实验其他:结构体中占字节大小问题:
#include <iostream>
using namespace std;
struct Student{
char a;
int b;
int c;
char d[5];
};
int main()
{
cout<<sizeof(double)<<endl;
cout<<sizeof(struct Student);
return 0;
}
由于结构体对齐问题,结构体在内存中存放是按单元存放的,
每个单元多大取决于结构体中最大基本类型的大小
因此代码中:最大单元为int 因此a先放,而b放不下同一单元,因此放第二单元(另一个4字节),c也是,而d为5个字节,因此占用两个单元,即8字节;因此代码中占用字节:4+4+4+8=20
struct Student{
char a;
int b;
short c;
};
字节:4+4+4=12
struct Student{
char a;
short b;
int c;
};
字节:4+4=8
struct Student{
char a;
char b[2];
char c[4];
};
字节:1+2+4=7
因此不提倡用第一种方法,浪费空间
实验3 简单应用 求圆柱体的体积
#include <iostream>
using namespace std;
#define PI 3.14159
int main(){
int radius,high;
double volume;
cout<<"Please input two numbers:"<<endl;
cin>>radius>>high;
volume=PI*radius*radius*high;
cout<<"radius:"<<radius<<" high:"<<high<<endl;
cout<<"The volume is:"<<volume<<endl;
return 0;
}
若输入3.8 5
则输出radius:3 high:0
The volume is:0
分析: