我正在製作一個非常簡單的「數學導師」程序,我需要顯示一個帶有4個選項的菜單:加,減,乘和退出。該程序應循環,直到我選擇退出。每次調用變量時,如何生成隨機數字?
到目前爲止,一切似乎都在起作用,但我無法弄清楚每次程序循環時如何創建一個新的隨機數。
下面是代碼:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int addFirstNum,
addSecondNum,
subFirstNum,
subSecondNum,
multFirstNum,
multSecondNum,
operNum,
num;
bool temBool = true; //Temporary boolean used in the while loop
unsigned seed; // Random generator seed
// Use the time function to get a "seed" value for srand
seed = time(0);
srand(seed);
//Random generated operands
addFirstNum = rand() % 40 + 10;
addSecondNum = rand() % 40 + 10;
subFirstNum = rand() % 40 + 10;
subSecondNum = rand() % 40 + 10;
multFirstNum = rand() % 40 + 10;
multSecondNum = rand() % 40 + 10;
while (temBool) //Start of the loop
{
// Menu of Math Tutor
cout << "Math Tutor - Main Menu";
cout << endl << endl;
cout << "1. Adittion\n";
cout << "2. Subtraction\n";
cout << "3. Multiplication\n";
cout << "4. Exit Program\n";
cout << endl << endl;
cout << "Choose your operation to practice (1-4) ";
cin >> operNum;
cout << endl << endl;
// Switch for the menu's options
switch (operNum)
{
case 1:
cout << "Working with addition\n";
cout << setw(3) << addFirstNum << "\n"
<< "+" << addSecondNum << "\n"
<< "---\n";
cout << "Your answer: ";
cin >> num;
if(num == addFirstNum + addSecondNum)
{
cout << "Correct answer: "
<< addFirstNum + addSecondNum << " Congratulations!\n";
}
else
{
cout << "Correct answer: "
<< addFirstNum + addSecondNum << " Sorry!\n";
}
cout << endl << endl;
break;
case 2:
cout << "Working with subtraction\n";
cout << setw(3) << subSecondNum << "\n"
<< "-" << multFirstNum << "\n"
<< "---\n";
cout << "Your answer: ";
cin >> num;
if(num == subSecondNum - multFirstNum)
{
cout << "Correct answer: "
<< subSecondNum - multFirstNum << " Congratulations!\n";
}
else
{
cout << "Correct answer: "
<< subSecondNum + multFirstNum << " Sorry!\n";
}
cout << endl << endl;
break;
case 3:
cout << "Working with multiplication\n";
cout << setw(3) << multFirstNum << "\n"
<< "*" << multSecondNum << "\n"
<< "---\n";
cout << "Your answer: ";
cin >> num;
if(num == multFirstNum * multSecondNum)
{
cout << "Correct answer: "
<< multFirstNum * multSecondNum << " Congratulations!\n";
}
else
{
cout << "Correct answer: "
<< multFirstNum + multSecondNum << " Sorry!\n";
}
cout << endl << endl;
break;
case 4:
cout << "Thank you for using Math Tutor.\n";
temBool = false;
break;
default: cout << "Incorrect menu seletion. Please choose between 1 and 4.\n";
return 0;
}
}
}
感謝您的快速響應!這似乎很明顯,但我試圖用這種方式編譯它,但我仍然沒有得到新的數字。 – RufioLJ 2014-10-07 09:07:10
我把你的代碼的開始,並把隨機數的代循環,並使其循環5次。檢查出來:http://ideone.com/KEW6cf – Baldrickk 2014-10-07 09:14:14
謝謝你看起來像它會工作,但我仍然有問題將它合併到我的代碼,以便它每次都會給我新的數字。例如,我選擇1(加法),然後在祝賀消息之後立即執行此操作,如果再次選擇1,我將得到相同的數字,而不是一組新的隨機數。我知道我在這裏錯過了一些小東西,但我看不到它。謝謝 – RufioLJ 2014-10-07 09:21:52