所以我遇到了另一个问题。我已经尝试了大约一个小时来解决这个问题,但没有成功。我不能让这个嵌套的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;
}
}它打印:(如果行=4,时间=3,字母= A)
%%%
%%%
%%%
%%%AAA发布于 2012-10-22 06:03:37
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-22 06:04:02
问题是,您似乎期望characterCount在循环的每次迭代中都获得其原始值。但是,因为您在内部循环中更改了它,所以它会到达-1,并且在您返回到0之前需要相当长的一段时间。您需要保留原始的characterCount,例如,使用专门针对每个循环的变量。
发布于 2012-10-22 06:00:13
打印一些有用的东西,比如characterCount和lineCount的值,而不是“%”。然后,您将看到您的循环正在做什么,并最终看到您做错了什么。
https://stackoverflow.com/questions/13002599
复制相似问题