首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复无限运行的嵌套while循环?

如何修复无限运行的嵌套while循环?
EN

Stack Overflow用户
提问于 2012-10-22 05:58:28
回答 5查看 1.2K关注 0票数 0

所以我遇到了另一个问题。我已经尝试了大约一个小时来解决这个问题,但没有成功。我不能让这个嵌套的while循环工作。代码应该根据输入放在行中,但目前它永远都在运行。

代码语言:javascript
复制
#include <iostream>
using namespace std;
void PrintLines(char characterValue, int characterCount, int lineCount);

// I'm going to have to change char characterValue to int characterValue
// will this still work if they are in seperate files?

void PrintLines(char characterValue, int characterCount, int lineCount)
    {
        while (lineCount--)                 //This is the problem
        {
            while (characterCount--)
            {
                cout << characterValue;
            }
            cout << "\n";
        }


    }

int main()
{

    char Letter;
    int Times;
    int Lines;

    cout << "Enter a capital letter: ";
    cin >> Letter;
    cout << "\nEnter the number of times the letter should be repeated: ";
    cin >> Times;
    cout << "\nEnter the number of Lines: ";
    cin >> Lines;

    PrintLines(Letter, Times, Lines);



    return 0;

当我执行此操作以检查它是否正常工作时。我看是这样的.

代码语言:javascript
复制
        while (lineCount--)                 //This is to check
        cout << "\n%%%";
        {
            while (characterCount--)
            {
                cout << characterValue;
            }
        }

它打印:(如果行=4,时间=3,字母= A)

代码语言:javascript
复制
%%%
%%%
%%%
%%%AAA
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-10-22 06:03:37

代码语言:javascript
复制
    while (lineCount--)                 //This is the problem
    {
        while (characterCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }

在lineCount的第一次迭代之后,characterCount为负。你不断递减它,它永远不会再次达到零,直到它溢出。

执行以下操作:

代码语言:javascript
复制
    while (lineCount--)                 //This is the problem
    {
        int tmpCount = characterCount;
        while (tmpCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }
票数 2
EN

Stack Overflow用户

发布于 2012-10-22 06:04:02

问题是,您似乎期望characterCount在循环的每次迭代中都获得其原始值。但是,因为您在内部循环中更改了它,所以它会到达-1,并且在您返回到0之前需要相当长的一段时间。您需要保留原始的characterCount,例如,使用专门针对每个循环的变量。

票数 2
EN

Stack Overflow用户

发布于 2012-10-22 06:00:13

打印一些有用的东西,比如characterCountlineCount的值,而不是“%”。然后,您将看到您的循环正在做什么,并最终看到您做错了什么。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13002599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档