c++ primer plus 第六版程式設計練習答案第二章
阿新 • • 發佈:2018-11-17
2.1
#include "stdafx.h" #include <iostream> using namespace std; int main() { char name[5],address[15]; cout << "enter your name\n"; cin >> name; cout <<"enter your address\n"; cin >> address; cout << "your name is " << name << endl << "your address is " << address<<endl; return 0; }
注:cin、cout可以用於字元陣列的輸入輸出且只需使用陣列變數名即可,注意:cin將空格、換行等字元預設為輸入字元陣列結束標誌
2.2
#include "stdafx.h" #include <iostream> using namespace std; int main() { int transe(int dis); int dis,dis_t; cout << "enter the distence"; cin >> dis; dis_t = transe(dis); cout << "the transform distance is " << dis_t << endl; return 0; } int transe(int dis) { int dis_t; dis_t = -dis; return dis_t; }
注意:在主函式中進行函式宣告
2.3
#include "stdafx.h" #include <iostream> using namespace std; int main() { void fun1(); void fun2(); fun1(); fun1(); fun2(); fun2(); return 0; } void fun1() { cout << "Three blind mice" << endl; } void fun2() { cout << "see how they run" << endl; }
2.4
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int year, month;
cout << "enter your age:";
cin >> year;
month = year * 12;
cout << "the month of your age is:" << month;
return 0;
}
2.5
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double transf(double degree);
double fahrent, dgree;
cout << "please enter a Celsius value:";
cin >> dgree;
fahrent=transf(dgree);
cout << dgree << " dgree Celsius is " << fahrent << " dgree Fahrenheit" << endl;
return 0;
}
double transf(double degree)
{
double fahren;
fahren = 1.8*degree + 32.0;
return fahren;
}
2.6
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double transf(double degree);
double liy, astu;
cout << "enter the number of light year:";
cin >> liy;
astu=transf(liy);
cout << liy<< " light year = " << astu << " astronomical units" << endl;
return 0;
}
double transf(double liy)
{
double ast;
ast = liy * 63240;
return ast;
}
2.7
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
void display(int h, int m);
int hour, minute;
cout << "Enter the number of huors:";
cin >> hour;
cout << "Enter the number of minutes:";
cin >> minute;
display(hour, minute);
return 0;
}
void display(int h,int m)
{
cout<<"Time: " << h << ":" << m;
}