我的任务有些麻烦。该程序的目的是要求用户输入由X组成的盒子的宽度和长度,并创建它,没有空格。我不确定为什么我的程序在输入长度和宽度为5时打印4个X,并且只打印出3行,底行有2个额外的X.
Input: Width: 5, Length: 5
Output:
XXXX
XXXX
XXXXXXX
Desired Output:
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
到目前为止,这是我的计划,非常感谢任何建议!
//Print a box of X's
#include <iostream>
using namespace std;
int main()
{
int length, width;
char character;
cout << "Please enter the length.";
cin >> length;
while (length < 0 || length > 25)
{
cout << "Invalid input. Try again." << endl;
cin >> length;
}
cout << "Please enter the width.";
cin >> width;
while (width < 0 || width > 25)
{
cout << "Invalid input. Try again." << endl;
cin >> width;
}
character = 'X';
for (int i = 1; i < length; ++i) //top
cout << character;
cout << endl;
for (int i = 1; i < width; ++i) //bottom
cout << character;
cout << endl;
for (int i = 1; i < length; i++) //left and right
cout << character;
for (int k = 1; k < width; k++)
cout << character;
cout << endl;
}
答案 0 :(得分:3)
尝试编写两个嵌套的for循环,它很容易使用长度和宽度,例如:
for(int i = 0; i < length;i++){
for(int j = 0; j < width; j++)
cout << 'X';
cout << endl;
}
答案 1 :(得分:0)
在C中制作一盒X的正确而有效的方法可以通过嵌套两个for循环来完成,一个用于长度,一个用于宽度。
这样,程序只需要制作一段长度的线,就像你想要宽度一样多。
而不是
for (int i = 1; i < length; ++i) //top
cout << character;
cout << endl;
for (int i = 1; i < width; ++i) //bottom
cout << character;
cout << endl;
for (int i = 1; i < length; i++) //left and right
cout << character;
for (int k = 1; k < width; k++)
cout << character;
你可以简单地说(注意我从0开始,而不是1)
for (int i = 0; i < length; i++) {
for(int j = 0; j < width; j++) {
cout << "X"
}
cout << endl;
}