C++ 學習之第二章編程練習題

目錄

介紹

編譯及運行環境

第一題

第二題

第三題

第四題

第五題

第六題 

第七題


介紹

本文是通過觀看C++ Primer Plus(第六版)進行學習之後的分享 。只是分享第二章的七個練習題

編譯及運行環境

我這裏直接是在Ubuntu 12.04.05 版本上使用Vim 編輯器純手敲代碼(初學者推薦,記憶更加深刻);

前兩章目錄見下圖

七個練習題如下圖所示,其中第七個練習題,我加入了循環判斷,可能不屬於第二章知識

第二章屬於基礎練習題,都比較簡單

簡單掌握預編譯命令,命名空間,函數的使用,甚至算上代碼格式規範等即可

第一題

簡單輸出自己的名字,地址

#include <iostream>

	using namespace std;
int main(){
	cout << "My Name is programmer" << endl;
	cout << "I am in shenzhen" << endl;
	
	return 0;
}

第二題

有學習函數(也叫方法)的使用

//練習題2 編寫一個C++程序,它要求用戶輸入一個以long爲單位的距離,然後將它轉換爲碼(一Long等於220碼)
#include <iostream>

using namespace std;
int temp(int);

int main(){
	cout << "請輸入一個數" <<  endl;
	int num;
	cin >> num ;
	cout << num << " Long = " << temp(num) << "碼\n";
return 0 ; 
}
int temp(int nums){
	return nums*220;
}

第三題

#include <iostream>

using namespace std;
void funOne();
void funTwo();

int main(){
	cout << "這是練習題三 " << endl;
	funOne();
	funOne();
	funTwo();
	funTwo();
return 0;
} 

void funOne(){
	cout << "Three blind mice" << endl;
}
void funTwo(){
cout << "See how they run" << endl;
}

第四題

有涉及到交互,這裏可以對比第五題發現有啥不同之處

#include <iostream>

using namespace std;
int ageToMonth(int ages){
return ages*12;
}

int main(){
	cout << "這裏是練習題4 " << endl;
	cout << "請輸入你的年齡: \n";
	int age;
	cin >> age ;
	cout << age <<  "歲包含" << ageToMonth(age) << "個月" << endl; 
return 0;
}

/*int ageToMonth(int ages){
	return ages*12;
}*/

第五題

#include <iostream>

using namespace std;

double tempTo(double);

int main(){
	double temp;
	cout << "Please enter a Celsius value:" << endl;
	cin >> temp;
	cout << temp <<  " degrees Celsius is " << tempTo(temp) << " degrees Fahrenheit. " << endl;
return 0;
}

double tempTo(double temp){
	double hua = 1.8*temp +32.0;
return hua;
}

第六題 

#include <iostream>

using namespace std;

double yearsTo(double);

int main(){
	cout << "Enter the number of light years: " << endl;
	double years;
	cin >> years;
	cout << years << " light years = " << yearsTo(years) << " astronomical units " << endl;
return 0;
}

double yearsTo(double year){
 return year*63240;
}

第七題

這裏有加入while 循環判斷時間大小的參數,如果不對會一直循環重新輸入三次,三次都不對的話則退出程序

#include <iostream>

using namespace std;
void addString(int,int);

int main(){
	cout << "這是C++ primer Plus(第六版) 第二章節的最後一道練習題 \n" ;
	cout << "Enter the number of hour: " << endl;
	int a,b,c;
	cin >> a;
	while(a>24){
	    c++;
	    if(c>3){
	        cout << "重新輸入三次錯誤,程序退出 \n";
	        return -1;
	    }
	    cout << "時間不能大於24 ,請重新輸入一個數 : " << endl;
	    cin >> a ;
	}
	cout << "Enter the number of minutes" << endl;
	cin >> b;
	while(b>60 ||  b<0){
	    cout << "分鐘數不能大於60小於0 ,請重新輸入 :" << endl;
	    cin >>b;
        }
	addString(a,b);
    return 0;
}

void addString(int a,int b){
	cout << "Time : " << a << ":" << b <<endl;
}

 

持續學習中,謝謝看到這篇文章的人,喜歡的話,點個贊再走,嘿嘿嘿

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章