定时C ++程序麻烦

时间:2014-04-18 16:11:28

标签: c++ time xcode5

我正在制作一个打字速度测试程序,它有一个需要运行60秒的循环然后退出并显示结果。我读过有关计时C ++程序的其他地方,但我的研究结果尚无定论。该程序正在出现(llbd),我希望有人能有解决方案/更好的方法来解决这个问题。此外,Xcode是目前唯一可用的软件。

#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

using namespace std;

string words[100];
string answer;
int rand_word = 0;
int speed = 0;
int wrong = 0;
int loop = 0;
clock_t t1;

void void_word();

int main(){

    char pause;
    cout << "Typing Speed Test" << endl;
    cout << "Press any Key to Continue";
    cin >> pause;
    t1 = clock();
    {
       if((t1/CLOCKS_PER_SEC) == 60){
           loop = 1;
       }
       void_word();
       cout << words[rand_word];
       cin >> answer;
       if(answer == words[rand_word]){
           speed ++;
       }
       if(answer != words[rand_word]){
           wrong ++;
       }
       srand (time(NULL)); // don't understand why underlined?
    }while (loop == 1)

    cout << "Your typing speed was " << speed << "WPM - with " << wrong << " wrong words" << endl;
    return 0;
}
void void_word(){
    rand_word = rand() % 40 + 1; // will change to ~ 100

    words[1] = "the";
    words[2] = "be";
    words[3] = "and";
    words[4] = "woman";
    words[5] = "good";
    words[6] = "through";
    words[7] = "child";
    words[8] = "there";
    words[9] = "those";
    words[10] = "work";
    words[11] = "should";
    words[12] = "world";
    words[13] = "after";
    words[14] = "country";
    words[15] = "pattern";
    words[16] = "it";
    words[17] = "enough";
    words[18] = "read";
    words[19] = "sit";
    words[20] = "right";
    words[21] = "tail";
    words[22] = "deep";
    words[23] = "dark";
    words[24] = "first";
    words[25] = "self";
    words[26] = "their";
    words[27] = "free";
    words[28] = "hundred";
    words[29] = "group";
    words[30] = "car";
    words[31] = "did";
    words[32] = "self";
    words[33] = "best";
    words[34] = "snow";
    words[35] = "language";
    words[36] = "pound";
    words[37] = "early";
    words[38] = "call";
    words[39] = "boat";
    words[40] = "light";
    return;
}

2 个答案:

答案 0 :(得分:1)

不完全确定你的问题是什么,所以这里有一些指示可以帮助你。

你错过了while循环的do - 实际循环的部分将是后面一行的cout

你不应该在循环中调用srand()。如果您的循环速度很快,那么time()会多次返回相同的值,这会导致srand()继续为随机数生成器播种相同的值,从而使rand()保持不变返回相同的值。

您还应该检查时间是> 60还是==,好像用户需要超过一秒的时间来输入可能错过第60秒的单词。

每次循环时你也不需要初始化单词列表,C中的数组从零开始而不是一个。

对所有内容使用全局变量是不必要的,而不是好的做法,你应该在函数中声明你的变量,尽可能使用它们。

答案 1 :(得分:0)

除了@MrZebra提出的观点之外,我想说:

使用clock是不合适的。它测量程序使用的处理器时钟。它不衡量实时。您应该使用time。主循环可以更改为:

time_t start;
time(&start);
do
{
   time_t now;
   time(&now);
   if(difftime(now, start) > 60)
   {
       break;
   }
   rand_word = rand() % 40 + 1; // will change to ~ 100
   cout << words[rand_word] << " " << flush;
   cin >> answer;
   if(answer == words[rand_word]){
       speed ++;
   }
   if(answer != words[rand_word]){
       wrong ++;
   }
}while (true);