C++学习之旅
- 今天学完C++ Primer Plus的第二章
main函数
#include<iostream>
using namespace std;
int main()
{
return 0;
}
如下用void来指定返回类型,说明函数没有返回值;正因为没有返回值,因此不能将函数调用放在赋值语句或其他表达式中,直接调用即可
void bucks(double);
bucks(4.5);
第二章书后习题
2-1
/*显示姓名和地址*/
#include <iostream>
using namespace std;
int main()
{
cout << "周周" << endl;
cout << "上海交通大学" << endl;
cin.get();
return 0;
}
2-2
/*输入以long为单位的距离,转换为码,1 long=220码*/
#include <iostream>
using namespace std;
int longtoyard(int);
int main()
{
cout << "please input a distance:";
int length = 0;
cin >> length;
int yard = 0;
yard = longtoyard(length);
cout << length<<"long = "<<yard<<"yards" << endl;
cin.get();
cin.get();
return 0;
}
int longtoyard(int distance)
{
int yards = distance * 220;
return yards;
}
2-3
/*使用用户定义的三个函数包括main生成下面的输出
Three blind mice
Three blind mice
See how they run
See how they run
其中一个函数调用两次生成前两行,另一个函数也调用两次生成其余的输出*/
#include <iostream>
using namespace std;
void firstsentence();
void secondsentence();
int main()
{
firstsentence();
firstsentence();
secondsentence();
secondsentence();
cin.get();
return 0;
}
void firstsentence()
{
cout << "Two blind mice" << endl;
}
void secondsentence()
{
cout << "See how they run" << endl;
}
2-4
/*用户输入一个年龄,显示该年龄包含几个月
Enter your age: 29*/
#include <iostream>
using namespace std;
int agetomonth(int);
int main()
{
cout << "Enter your age: ";
int age = 0;
cin >> age;
int months = 0;
months = agetomonth(age);
cout << "you have lived for " << months << " months" << endl;
cin.get();
cin.get();
return 0;
}
int agetomonth(int age)
{
int months = 12 * age;
return months;
}