首页 > 解决方案 > 在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;
}

标签: c++while-loopbooleaninfinite-loop

解决方案


#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 循环,并确保使计数器变量之一浮动,否则对于少数测试用例,您最终将百分比为零。


推荐阅读