//--《C++捷径教程》读书笔记--Chapter 2--C++概述
//--Chapter 2--C++概述
//--11/7/2005 Mon..
//--Computer Lab
//--Liwei
所有程序在正常结束时都应该返回0。
函数不能嵌套定义。
唯一不需要原型声明的函数是main()。因为系统已经预定义了。
//--程序#1 第一个C++程序
#include <iostream>
using namespace std;
int main()
{
cout<<"This is my first C++ program."<<endl;
return 0;
}
//--程序#2 使用一个变量
#include <iostream>
using namespace std;
int main()
{
int x;
x=1023;
cout<<"This program prints the value of x:";
cout<<x<<endl;
return 0;
}
//--程序#3 将加仑换算成公升数
#include <iostream>
using namespace std;
int main()
{
int gallons,liters;
cout<<"Enter number of gallons:";
cin>>gallons;
liters=gallons*4;
cout<<"Liters:"<<liters<<endl;
return 0;
}
//--程序#4 使用浮点数将加仑换算成公升数
#include <iostream>
using namespace std;
int main()
{
double gallons,liters;
cout<<"Enter number of gallons:";
cin>>gallons;
liters=gallons*3.7854;
cout<<"Liters:"<<liters<<endl;
return 0;
}
//--程序#5 包含两个函数
#include <iostream>
using namespace std;
void myfunc();
int main()
{
cout<<"In main()"<<endl;
myfunc();
cout<<"Back in main()"<<endl;
return 0;
}
void myfunc()
{
cout<<"Inside myfunc() "<<endl;
}
//--程序#6 使用函数abs()
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout<<abs(-10)<<endl;
return 0;
}
//--程序#7 演示调用函数的简单示例
#include <iostream>
using namespace std;
void mul(int x,int y);
int main()
{
mul(10,20);
mul(5,6);
mul(8,9);
return 0;
}
void mul(int x,int y)
{
cout<<x*y<<" "<<endl;
}
//--程序#8 演示返回一个值的函数的简单示例
#include <iostream>
using namespace std;
int mul(int x,int y);
int main()
{
int answer;
answer=mul(10,11);
cout<<"the answer is:"<<answer<<endl;
return 0;
}
int mul(int x,int y)
{
return x*y;
}
//--程序#9 /n的使用
#include <iostream>
using namespace std;
int main()
{
cout<<"one/n";
cout<<"two/n";
cout<<"three";
cout<<"four"<<endl;
return 0;
}
//--程序#10 if语句的使用
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter first number: ";
cin>>a;
cout<<"Enter second number: ";
cin>>b;
if(a<b)
cout<<"First number is less than second./n";
return 0;
}
//--程序#11 for语句的使用
#include <iostream>
using namespace std;
int main()
{
int count;
for(count=1;count<=1000;count++)
cout<<count<<" ";
cout<<endl;
return 0;
}
//--程序#12 代码块的使用
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter first number:";
cin>>a;
cout<<"Enter second number:";
cin>>b;
if(a<b)
{
cout<<"First number is less than second./n";
cout<<"Their difference is : "<<b-a<<endl;
}
return 0;
}