模板:程式設計-10102-期中考術科

出自 陳富國維基館
前往: 導覽搜尋

第一題

題目:將下列程式以遞迴方式重寫

void main(){
  int i, j;
  for (int i = 8; i >= 1 i-=2){
    for (int j = 8; j >= 1; j-=2){
      cout << i << "*" << j << "=" << i*j<< "  ";
    }
  }
}
  • 底下我示範九九乘法表的解法:
#include <iostream>
#include <iomanip>

using namespace std;

/*
注意:下面遞迴用法,若是先遞回後印,則為遞增,若是先印後遞回,則為遞減

*/

void LoopJ1(int j, int i, int min){
	if (j > min) LoopJ1(j-1, i, min);
	cout << i << "*" << j << "=" << setw(2) <<  i*j<< "  ";
}

void LoopI1(int i, int min){
	if (i > min) LoopI1(i-1, min); 
	LoopJ1(9, i, min);
	cout << endl;
}


void LoopJ2(int j, int i, int min){
	cout << i << "*" << j << "=" << setw(2) <<  i*j<< "  ";
	if (j > min) LoopJ2(j-1, i, min);
}

void LoopI2(int i, int min){
	LoopJ2(9, i, min);
	cout << endl;
	if (i > min) LoopI2(i-1, min); 
}

void main(void){
	cout << "迴圈遞增示範:"<< endl;
	for (int i = 1; i <= 9; i++){
		for (int j=1; j <= 9; j++){
			cout << i << "*" << j << "=" << setw(2) <<  i*j<< "  ";
		}
		cout << endl;
	}
	
	cout << "遞迴遞增示範:"<< endl;
	LoopI1(9,1);

	cout << "迴圈遞減示範:"<< endl;
	for (int i = 9; i >= 1; i--){
		for (int j=9; j >= 1; j--){
			cout << i << "*" << j << "=" << setw(2) <<  i*j<< "  ";
		}
		cout << endl;
	}

	cout << "遞迴遞減示範:"<< endl;
	LoopI2(9,1);
	system("pause");
}

第二題

由檔案Midtest.txt讀入資料,檔案資料為字串與整數混合,將檔案中的整數讀取出來,計算這些整數的個數與總和,並將結果存入另一個檔案MidTestResult.txt中。 Midtest.txt資料檔內容如下:

7525001aaaaa83a90a657525002a75a63a657525003a7

9a95a507525004a95a95a917525005a88a60a10075250

06a78a87a557525007a86a76a827525008a82a60a8575

25009a76a60a707525010a66a57a477525011a75a75a5

5
7525012a71a45a68
7525013a89aaaaa82a85
7525014a41a35a46
7525015a63a42a51
7525016a65a42a55
7525017a64a35a58
7525018a63a55a42
7525019a32a21a65
7525020a81a55a86
7525021a70a48a65
7525022a64a60a40
7525023a58a65a20
7525024a77a75a60
7525025a71a73a47
7525026a72a60a50
7525027a51a33a27
7525028a72a70a52
7525029a70a90a32
7525030a62a65a30
7525031a59a60a27
7525032a84a80a75
7525033a72a60a55
7525034a69a46a53
7525035a97a90a86
7525036a50a45a17
7525037a58a35a43

參考示範(只抓出上面資料檔中的整數值,個數與總和程式碼請自行加入)

#include <iostream>
#include <fstream>
using namespace std;

void main(void){

    ifstream file;       // 建立檔案輸出、輸入物件 
    char ch;
    int num=0;
    file.open("c:\\temp\\MidTest.txt",ios::in);
    if (!file){
      cout << "檔案開啟錯誤\n";
    } else{
      do{
	file.get(ch);
	if (ch >= '0' && ch <= '9')	{//若字元為'0'~'9'的話
	  num = num *10 + (ch-'0');
	  file.get(ch); //讀下一個字元
	  while (ch >= '0' && ch <= '9'){
	    num = num *10 + (ch-'0');
	    file.get(ch); //讀下一個字元
	    if (file.eof()) break;
	  }
	  cout << num << endl;
	  num = 0;
	}
     } while(!file.eof());
     file.close();
   }
   system("pause");
}