c++ - 乘法游戏循环幻灯片问题

标签 c++ math testing while-loop conditional-statements

所以我决心制作一款史诗般的基于数学控制台的有趣游戏。

我很好奇为什么当随机数输入零时,程序会滑过一系列乘以 0 并跳过我代码中的“请输入:”部分。这是因为 true 和 false bool 特性while循环中的测试条件?更重要的是,我怎样才能阻止这种情况发生?

感谢大家的帮助!

enter image description here

// 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,您假设答案是错误的,但是如果 ab设置为零,cd 在您的用户可以输入数字之前是相等的。一种解决方案是使用 do { ... } while ( ... ); 循环而不是 while 循环,以确保始终要求用户输入数字在执行正确答案测试之前。

关于c++ - 乘法游戏循环幻灯片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055251/

相关文章:

c++ - 结构中成员的默认值

math - 整数存储为 float

testing - TestCafe RequestLogger - 在对每个请求对象进行断言之前如何等待所有响应返回

testing - 故意插入恶意软件

c++ - 测试对象是否被删除

c++ - 使用 fstream 的“访问冲突”

c++ - QWidget - 不确定从哪里开始

c++ - 阻止进程使用 WMI 启动?

java - 将 int 分成整数

c - 尝试为 hermite 多项式暴力求根