#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int i = 0;
int j = 0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
while (i <= arrowBaseHeight){
while (j <= arrowBaseWidth){
cout << "*";
j++;
}
cout << endl;
j = 0;
i++;
}
// Draw arrow head (width = 4)
return 0;
}
我正在尝试编写一个简单的程序,它需要3个用户输入的整数并将它们分配给arrowBaseHeight,arrowBaseWidth和arrowHeadWidth。输出应该是一系列打印出来的星号(*),如:
**
**
**
****
***
**
*
创建箭头图像。
我一直试图找出使用嵌套循环打印箭头基部的最佳方法(我一直在使用,但如果是更好,请告诉我)。我已经尝试了多种不同的方法,我还没有想出一个不会丢失错误的方法。我还没有到达箭头部分,但如果有人想指出我正确的方向,那将是有帮助的!
答案 0 :(得分:1)
你很接近,但是如果你想让一个循环完全执行n
次,在0开始你的计数器i
,条件应该是i < n
,而不是{{1 }}
关于头部,您只需要从输入的宽度开始减少每行中打印的字符数。
i <= n
你可以看到很多重复的代码,考虑使用一些自定义函数来重构它。
答案 1 :(得分:0)
您应该将while循环的条件更改为:
while (i < arrowBaseHeight)
和
while (j < arrowBaseWidth)
。
对于arrowHeadWidth,您可以尝试获取arrowBaseHeight的中间值。也许是这样的
int r = 0;
if(i == arrowBaseHeight / 2)
{
while(r < arrowHeadWidth)
{
cout << "*";
r++;
}
}
我还没有测试过。我希望它有所帮助。
答案 2 :(得分:0)
您需要做的就是添加一个新变量,它可以指示您现在需要打印什么。 规则是:
If:
高达一半的“arrowBaseHeight”迭代需要打印基础
Else:
打印头部,然后减少1
另外finger rule
- 如果你正在使用“while”而你需要增加一个迭代器,它总是表明你需要使用For
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int arrowBaseHeight = 0;
int arrowBaseWidth = 0;
int arrowHeadWidth = 0;
int newArrowBaseWidth=0;
cout << "Enter arrow base height:" << endl;
cin >> arrowBaseHeight;
cout << "Enter arrow base width:" << endl;
cin >> arrowBaseWidth;
cout << "Enter arrow head width:" << endl;
cin >> arrowHeadWidth;
cout << endl;
// Draw arrow base
for(int i=0; i < arrowBaseHeight; i++){
newArrowBaseWidth= i < arrowBaseHeight/2 ? arrowBaseWidth : arrowHeadWidth--;
for(int j=0; j < newArrowBaseWidth; j++){
cout << "*";
}
cout << endl;
}
// Draw arrow head (width = 4)
return 0;
}
另一件事是,如果您想要迭代n
时间,则需要将条件从=<
更改为{n = 1次}到<