gpt4 book ai didi

c++ - 定时 C++ 程序问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:36 27 4
gpt4 key购买 nike

我正在制作一个打字速度测试程序,它有一个循环需要运行 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 而不是 ==,就好像用户输入单词的时间超过 1 秒,它可能会错过第 60 秒.

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

对所有事物都使用全局变量是不必要的,也不是好的做法,您应该在函数中尽可能使用它们的地方声明变量。

关于c++ - 定时 C++ 程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23157915/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com