所以我决心制作一款史诗般的基于数学控制台的有趣游戏。
我很好奇为什么当随机数输入零时,程序会滑过一系列乘以 0 并跳过我代码中的“请输入:”部分。这是因为 true 和 false bool 特性while循环中的测试条件?更重要的是,我怎样才能阻止这种情况发生?
感谢大家的帮助!
// multiplicationgame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void game();
int _tmain(int argc, _TCHAR* argv[])
{
// waiting.cpp : Defines the entry point for the console application.
//
cout << "Welcome to Math game!\n\n" << endl;
float secs;
secs = 3;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start < delay )
;
char choice = 'z';
game();
while(choice != 'n')
{
cin >> choice;
if (choice == 'y')
{
cout << "\n\n";
game();
}
else
choice = 'n';
}
return 0;
}
void game()
{
float secs;
secs = 33;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
int correct = 0;
while (clock() - start < delay )
{
srand(time(NULL));
int a = rand() % 23;
int b = rand() % 23;
int c = (a * b);
int d = 0;
char choice = 0;
cout <<"What does " << a << " * " << b << " equal?" << endl << endl << endl;
cout << "\n";
while(d != c)
{
cout << "Please enter a number: ";
cin >> d;
if(d == c)
++correct;
}
cout << "\n\nCorrect! " << (a * b) << " is the answer!" << endl << endl;
}
cout << "Your score is: " << correct << "\n\n" <<endl;
cout << "Would you like to play again (Y) or (N)?\n\n\n";
}
最佳答案
如果 c
不等于 d
,您假设答案是错误的,但是如果 a
或 b
设置为零,c
和 d
在您的用户可以输入数字之前是相等的。一种解决方案是使用 do { ... } while ( ... );
循环而不是 while
循环,以确保始终要求用户输入数字在执行正确答案测试之前。
关于c++ - 乘法游戏循环幻灯片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055251/