C++ 實驗二 類和對象

實驗二 類和對象

一、目的要求
1、理解面向對象的程序設計的特點;
2、學會類和對象的定義以及對象成員的引用;
3、理解類的封裝性和信息隱藏,學會類聲明和成員函數定義的分離。
二、實驗內容與步驟
1.設計一個類,成員變量包括學號、姓名、性別、年齡、成績;
2.完成以下:
(1)由鍵盤分別輸入n個學生的學號、姓名、性別、年齡、成績;
(2)計算每個學生的平均成績;
(3)判斷每個學生是否有不及格的課程;
(4)並輸出所有學生的信息和平均成績;
三、上機要求
1.類聲明放在頭文件(.h)中;
2.成員函數定義放在源文件(.cpp)中;
3.主函數放在源文件(file.cpp)中。
附代碼
!!!編譯環境 DevC++ 5.11 TDM-GCC 4.9.2 64-Bit Release
頭文件 iquery.h

#ifndef  _IQUERY_H
#define _IQUERY_H 1
    using std::string;
	#define MAXN 100 

	class student{
		private:
			int old;
			string sex;            
			string name;
			string number; 
			double chinese;
			double math;
			double english;
			double daniel;
			double ave_grade;
	public:	
		void data_input();
//		double data_grade_calc();   
		bool data_grade_judge();    //judge 每個學生成績是否及格 
		void data_output();
		
	};
#endif

頭文件實現文件 iquery,cpp

#include <iostream>
#include "string"
#include "iquery.h"
#include "iomanip"
using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void student :: data_input(){
		cout<<"    姓名:" ;cin>>name;
		cout<<"    年齡:" ;cin>>old; 
		cout<<"    性別:" ;cin>>sex;
		cout<<"    學號:" ;cin>>number;
		cout<<"接下來依次輸入語文,數學,英語,理綜成績"<<endl;
		cin>>chinese>>math>>english>>daniel;
		ave_grade=(math+chinese+english)/3;
}

//double student :: data_grade_calc(){           //計算主科平均成績 
//	return (math+chinese+english)/3;
//}
bool student :: data_grade_judge(){
	while(chinese<90||math<90||english<90){
		return 1;
	}
	return 0;	
}
void student :: data_output(){
	cout<<setiosflags(ios::left);
	cout<<"    姓名:" <<name<<endl;
	cout<<"    年齡:" <<old<<endl;
	cout<<"    性別:" <<sex<<endl;
	cout<<"    學號:" <<number<<endl;
	cout<<setw(10)<<"    語文:" <<setw(6)<<chinese<<setw(6)<<"數學:"<<setw(6)<<math<<setw(6)<<"英語:"<<setw(6)<<english<<endl;
	cout<<"    平均成績:"<<ave_grade<<endl; 
	
}

簡陋的源碼 main.cpp

#include <iostream>
#include "iquery.h"
#include "iomanip"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
	int ele=0;
	char sel;
	int pos;
	student stu[MAXN];
	int i=0;
	int n=0; 
	int choice;
	 
	cout<<"請輸入學生個數:"<<endl;
	cin>>n;
	do{
		cout<<"請輸入第"<<i+1<<"個學生信息"<<endl;
		fflush(stdin);
		stu[i].data_input();
		i++;
		cout<<endl;
	}while(i<n);
	
	for(i=0;i<n;i++){
		cout<<"學生"<<i+1<<endl; 
		stu[i].data_output();
		if(stu[i].data_grade_judge())
		cout<<"    該學生有不及格課程."<<endl; 
		else cout<<"    該學生沒有不及格課程."<<endl; 
	}
	return 0;
	}

歡迎訪問陳風的個人博客

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