0

だから私は別の問題に直面しています。私は運がないので、これを約1時間修正しようとしています。このネストされた while ループを機能させることができません。コードは入力に従って行を挿入する必要がありますが、現在は永遠に続いています。

#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;

これを行うと、正しく機能するかどうかを確認します。私はそれが...

        while (lineCount--)                 //This is to check
        cout << "\n%%%";
        {
            while (characterCount--)
            {
                cout << characterValue;
            }
        }

:( Lines = 4 and Times = 3 and Letter = A の場合)

%%%
%%%
%%%
%%%AAA
4

5 に答える 5

2
    while (lineCount--)                 //This is the problem
    {
        while (characterCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }

lineCount の最初の繰り返しの後、characterCount は負になります。デクリメントし続けると、オーバーフローするまで再びゼロになることはありません。

行う:

    while (lineCount--)                 //This is the problem
    {
        int tmpCount = characterCount;
        while (tmpCount--)
        {
            cout << characterValue;
        }
        cout << "\n";
    }
于 2012-10-21T22:03:37.040 に答える
2

characterCount問題は、ループの反復ごとに元の値を取得することを期待しているように見えることです。ただし、内側のループで変更するため、 に-1到達し、 に戻るまでにかなりの時間がかかります0characterCountたとえば、ループごとに変数を使用するなど、オリジナルを維持する必要があります。

于 2012-10-21T22:04:02.070 に答える
1

"%%%" の代わりに、characterCountやの値のような便利なものを表示しますlineCount。次に、ループが何をしているのか、最終的には何が間違っていたのかがわかります。

于 2012-10-21T22:00:12.723 に答える
0

これでコードが修正されます。あなたcharacterCountはゼロ以下に減少し、私はこれを防ぎました:

void PrintLines(char characterValue, int characterCount, int lineCount)
{   
    while (lineCount--)                 
    {   
        int cCount = characterCount;//This was the problem

        while (cCount--) // and this fixes it
        {   
            cout << characterValue;
        }   

        cout << "\n";
        cCount = characterCount ; 
    }   

}  
于 2012-10-21T22:04:00.290 に答える
0

ネストされたループを使用するように制約されていない限り、次のようなことを行う方がおそらく簡単です。

// Beware: untested in the hopes that if you use it, you'll need to debug first
std::string line(Times, Letter);

std::fill_n(std::ostream_iterator<std::string>(std::cout, "\n"), 
            lineCount,
            line);
于 2012-10-21T22:22:59.877 に答える