gpt4 book ai didi

c++ - While 在 C++ 中使用定时器循环

转载 作者:行者123 更新时间:2023-11-30 01:21:45 25 4
gpt4 key购买 nike

我正在尝试创建一个 while 循环,当满足字符串条件或计时器条件时,程序将跳出循环并打印出所需的输出。并且在打印出所需的输出时,输出将包含比较答案前后的时间差。

但是循环没有按照我期望的方式运行。那么谁能帮我找出这段代码的问题在哪里?

下面是我的代码:

void startGame(time_t cd,int gl){
string guessWord;
time_t start, end, diff,timeLeft;

cout << "Scrambled word is " << randomizeWord(gl) << endl;

while (timeLeft != cd || guessWord.compare(originalWord) == 0)
{
start = time(0);
cout << "You have " << cd << " seconds to guess." << endl;
cout << "Enter guess : ";
cin >> guessWord;
end = time(0);
diff = end - start;
//total_time = total_time + diff;
timeLeft = cd - diff;

if(guessWord.compare(originalWord) != 0)
{
cout << "WRONG! Attempt ... You have " << timeLeft << "seconds left... Try Again" << endl;
cout << "Enter guess : ";
cin >> guessWord;
}
else
{
cout << "You are CORRECT! "<< timeLeft <<" seconds left. Your timing is "<< diff <<" seconds." << endl;
break;
}
}
}

最佳答案

条件说明

也改变你的循环条件:

while ((timeLeft <= cd) && (guessWord.compare(originalWord) != 0))

如果其中一个条件失败,你就会爆发。这是因为如果任一条件失败,&& 的结果为 false。所以这将继续,而 a) 您还有时间并且 b) 您还没有猜到这个词。您对 || 的使用将使循环继续,而其中一个为真(因此两者都必须失败才能退出循环)。

注意:我个人认为额外的大括号 () 很适合让表达式更易于阅读。对于没有经验的程序员,他们不需要猜测(查找)优先顺序

剩余时间计算:

time_t start    = time(0);  // Make the start time absolute and outside the loop.
// Note: Use one line per variable declaration and initialize.
int timeLeft = cd; // timeLeft is a relative value that can be negative => `int`

// Notice I adjust timeLeft because of new definition.
while ((timeLeft > 0) && (guessWord.compare(originalWord) != 0))
{
time_t end = time(0);
time_t timeTaken = end-start; // Total time taken so Far.
timeLeft = cd - timeTaken; // Time left is thus.

关于c++ - While 在 C++ 中使用定时器循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657409/

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