在做一段时间内检查字符的无限循环



目标是计算超过 10 的分数百分比。分数介于 0 和 20 之间。当我单击"N"时,我的 while 循环有问题。我得到一个无限循环。

#include <iostream>
int main() {
float MARK, PERCENTAGE;
int NBR_MARK, NBR_MARK_10;
MARK = 0;
NBR_MARK = 0;
NBR_MARK_10 = 0;
PERCENTAGE = 0;
char R = 'N';
std::cout << "Enter a mark ?" << std::endl;
std::cin >> MARK;
while (MARK < 0 || MARK > 20) {
std::cout << " Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
}
std::cout << "Do you want to enter a new mark ?" << std::endl;
std::cout << "Click on 'O' to continue and on 'N' to stop" << std::endl;
std::cin >> R;
if ((R != 'N') || (R != 'n'))
std::cout << "You will continue" << std::endl;
do {
std::cout << "Enter a new mark" << std::endl;
std::cin >> MARK;
std::cout << std::endl;
while ((MARK < 0) || (MARK > 20)) {
std::cout << "Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
std::cout << std::endl;
}
NBR_MARK++;
if (MARK > 10) NBR_MARK_10++;
std::cout << "To stop press 'N'" << std::endl;
std::cin >> R;
}
while ((R != 'N') || (R <= 'n'));
PERCENTAGE = NBR_MARK_10 / NBR_MARK * 100;
std::cout << "Le % de notes > 10 est de: " << PERCENTAGE << " %" << std::endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
float MARK=0.0, PERCENTAGE=0.0;
int NBR_MARK_10;
float NBR_MARK = 0.0;
NBR_MARK_10 = 0;
char R = 'a';
while(R!='N')
{
std::cout << "Enter a mark ?" << std::endl;
std::cin >> MARK;
while (MARK < 0 || MARK > 20) {
std::cout << " Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
}
NBR_MARK+=1.0;

if (MARK > 10) NBR_MARK_10++;

std::cout << "Do you want to enter a new mark ?" << std::endl;
std::cout << "Click on 'O' to continue and on 'N' to stop" << std::endl;
cin >> R;

}
PERCENTAGE = (NBR_MARK_10 / NBR_MARK) * 100;
std::cout << "Le % de notes > 10 est de: " << PERCENTAGE << " %" << std::endl;
return 0;
}

在检查 R 的下一个输入时使用 while 循环,并确保将其中一个计数器变量设置为浮动,否则您最终会在少数测试用例中将获得零百分比。

代码有两个问题。正如Sharath Chander P指出的那样,代码流中显然存在逻辑问题。即使你按"N"(第一次(,里面的代码块也会这样做。而将执行,因为只有在执行 do 中的所有语句后才会检查条件。而循环。

现在回答你关于无限循环的问题。这是因为当您按下"N"键时,表达式while ((R != 'N') || (R <= 'n'));将是"true"。当您按"N"时,R 的值将为 78(ASCII 值为"N"(。由于 ASCII 值"n"为 110,因此检查R<='n'将返回 true。(显然 78 小于 110。

由于(R!='N')为假,R<='n'为真,因此表达式while ((R != 'N') || (R <= 'n'));将被计算为while(false || true)

由于结果将是"true",因此循环将继续。

现在,如果您按"n",则表达式将被计算为while(true || true)这也将导致"true"并且循环将继续;