定时C++程序故障

Timed C++ Program Trouble

本文关键字:故障 程序 C++ 定时      更新时间:2023-10-16

我正在制作一个打字速度测试程序,该程序有一个循环,需要运行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;
}

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

while循环缺少do——实际循环的部分将是后面一行的cout

您不应该循环调用srand()。如果循环很快,那么time()将多次返回相同的值,这将导致srand()继续为随机数生成器设定相同值的种子,这反过来又将使rand()继续返回相同值。

您还应该检查时间是否是> 60而不是==,就好像用户需要一秒钟以上的时间才能键入可能会错过第60秒的单词一样。

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

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

除了@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);