编写猜数小游戏。要去玩家从数列中猜一个数,每猜对一个加一分,并(使用文件)记录玩家的最高分。
//----斐波那契数列 猜数游戏---- //----时间:2019.11.20--------- // #include<vector> #include<string> #include<iostream> #include<fstream> #include<cstdlib> #include<time.h> using namespace std; //斐波那契数列生成函数 //输入参数:int 数列大小 //返回值:斐波那契数组首地址 const vector<int>* fibon_seq(int size) { static vector<int> elems; const int max_size = 1024; if (size <= 0 || size > max_size) { cerr << "错误的大小\n"; return 0; } for (int ix = elems.size(); ix < size; ++ix) { if (ix == 0 || ix == 1) elems.push_back(1); else elems.push_back( elems[ix - 1] + elems[ix - 2]); } return &elems; } void write_score_file(string user_name,int num_right) { ofstream outfile("score.txt",ios_base::app); //追加模式打开 if (!outfile) { cerr << "无法打开score.txt\n"; } else { outfile << user_name<<' '<<num_right<<endl; } } void read_score_file(string &user_name, int & num_right) { ifstream infile("score.txt"); if (!infile) { cerr << "无法打开文件score.txt\n"; } else { string name; int n_right; while (infile >> name) { infile >> n_right; if (name == user_name && n_right>num_right) { num_right = n_right; } } } } int main() { string user_name; int num_right = 0; int highest_score = 0; //最高分 cout << "Please enter your name:"; cin >> user_name; cout << "\n" << "Hello," << user_name <<endl; int fibo_size = 10; const vector<int>* fibo = fibon_seq(fibo_size); for (int i = 0; i < (*fibo).size(); i++) { cout << "第" << i + 1 << "个:" << (*fibo)[i] << ' '; if ((i + 1) % 3 == 0) cout << "\n"; } cout << endl; bool willing_try = true; while (willing_try) { srand((unsigned)time(NULL)); int index = rand() % fibo_size; cout << "猜一个数:"; int n; cin >> n; if (n == (*fibo)[index]) { cout << "猜对了\n再猜一次吗(y\n)"; num_right++; } else { if (n > (*fibo)[index]) cout << "太大了\n"; else cout << "太小了\n"; cout << "再猜一次吗(y\n):"; } char choice; cin >> choice; if (choice != 'y' && choice != 'Y') { willing_try = false; } } if (num_right > highest_score) { cout << "\n----新纪录: " << num_right<<"----"<< endl; write_score_file(user_name, num_right); } return 0; }