乘法游戏循环幻灯片问题

时间:2014-01-10 22:02:57

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

因此,我决心制作一款基于史诗般数学控制台的游戏。

我很好奇为什么当随机输入零时,程序滑过一系列乘以0并跳过我的代码的“请输入:”部分..这是因为真假布尔特征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";
}

5 个答案:

答案 0 :(得分:0)

如果c不等于d,但假设ab设置为零,c和{在用户输入数字之前,{1}}是相等的。一种解决方案是使用d循环而不是do { ... } while ( ... );循环来确保在测试之前始终要求用户输入正确答案。

答案 1 :(得分:0)

正如Markku所说,不要设置d = 0,因为如果a或b等于0,那么c = a * b = 0然后你的while循环条件c!= d将不会保持,所以它将被跳过

答案 2 :(得分:0)

您将d初始化为0,任何时间0都为0.因此(d!= c)条件将始终为false,并且您不输入while(d!= c)循环。

你多次得到0,因为while循环很快完成,所以当你调用srand(time(NULL))时,time(NULL)将返回与之前的itteration相同的值,并且你得到相同的随机种子(再次给你0)。

将d初始化为-1(或a * b不能为的其他值)。将srand移到while循环之外 - 你只需要(并且应该)在程序中调用srand一次。

约翰

答案 3 :(得分:0)

快速修复:初始化int d = -1;而不是int d = 0;

您正在初始化int c = a * b。由于ab为零,因此乘法导致c为零。您还初始化int d = 0;。然后你有while(d != c),但是你把它们分配给零,因此你的程序跳过那个循环,因为d != c是假的。

答案 4 :(得分:0)

  

@AEGIS不,srand(time(NULL))只是根据程序运行时的当前时间为随机数生成器播放一个稍微随机的值。这可以确保程序的每次运行都会产生一组不同的乘法问题来解决。

     

@AEGIS外部while(clock() - start&lt; delay){...}循环在“延迟”时间到期时终止。当a或b为零时,内部while(d!= c){...}循环根本不会输入,或者只要用户输入错误答案就永远循环。因此,虽然这在实践中不是一个真正的问题 - 任何用户都可能最终得到正确答案或手动中止程序 - 这是一个不一定会终止的程序。

@Ned Nowonty看着屏幕截图AEGIS提供的外环没有终止。如果它确实那么

  

您的分数是:(某些数字)

     

你想再玩(Y)还是(N)?

会出现。当您使用相同的初始化程序进行srand时,最终会得到相同的伪随机数。因此,当其中一个变量初始化为0时,它会循环,直到时间(NULL)为srand提供不同的变量。为了避免你可以使用迭代器和时间函数,所以种子会一直不同。

相关问题