c++ - 在do while中检查字符的无限循环
问题描述
目标是计算分数超过 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 循环,并确保使计数器变量之一浮动,否则对于少数测试用例,您最终将百分比为零。
推荐阅读
- c# - 如何使用静态方法初始化 ServiceBusConnectionStringBuilder 对象并重置它 c#
- ionic-framework - Ionic 4、Azure Active Directory B2C 与 Google 作为身份提供者
- php - 如何为管道“|”编写选择查询 列中的分隔值?
- c++ - C++ DLL(不是 CLI)可以调用 .NET Core 3.0 委托吗?
- xcode - 在 xcode 中加载应用程序时,Cordova ios 插件在构建完成后失败
- c# - 从其他页面更改 MainWindow 内容
- python - Jupyter Notebook ModuleNotFoundError:没有名为“graphviz”的模块
- mysql - MySQL - 大写每个单词的第一个字母,包括土耳其语字符
- reactjs - 使用 react-testing-library 在 useEffect 中测试 api 调用
- javascript - Javascript:动态加载 JSON(取决于文件数量)