以C++输出一个数字三角形
Output a triangle of numbers in C++
我的任务是要求用户输入int
,然后输出如下所示的"数字三角形"(在这种情况下,int
等于5
(。
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
但是,我为此任务编写的代码输出以下内容:
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
作为参考,这是我的代码:
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Size: " << std::endl;
cin >> size;
for(int i = size; i >= 0; i--)
{
for(int j = 0; j <= i; j++)
{
if (j < i){
cout << j << " ";
}
else{
cout << j << " ";}
}
cout << endl;
}
return 0;
}
有人可以告诉我在我的程序中要更改什么以使其输出正确的三角形吗?提前谢谢。
您应该在行的开头而不是结尾打印空格。
for(int i = size; i >= 0; --i){
for(int j = 0; j < size-i; ++j){cout << " ";} // spaces at the beginning
for(int j = 0; j <= i; ++j){
cout << j << " ";
}
cout << endl;
}
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 以C++输出一个数字三角形
- 反转一个数字程序不起作用,为什么?
- 如何让用户在 c++ 中选择一个数字
- 输出一个数字,该数字可能是三种类型之一
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- C++[递归]将一个数字写成2的升序之和
- 试图找到一个数字的平方根,但代码不起作用。C++
- 我没有得到一个数字作为输出,而是一个表情符号
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 你怎么编码,如果x不等于一个数字,程序就会退出
- 如何将整数数组相乘得到一个数字?
- 为无符号字符* 分配一个数字
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 字符串和双精度的麻烦,等值后再得到一个数字