输出看起来像在C三角形 [英] Output that looks like a triangle in C

查看:101
本文介绍了输出看起来像在C三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个程序,

include <stdio.h>

int main(){
int size = 5;

int row;
int col;

  for (col=0; col<size; col++){
    for (row=0; row<col;row++){
      printf(" ");
    }

    for (row=0; row <(size-col) ; row++){
      printf("*");
    if(col<=size){
      printf("*");
      }
    }
    printf("\n");
  }
  return 0;
}

它应该像一个三角形

It should make a triangle like

*********
 *******
  *****
   ***
    *

但是,相反还有一个额外的*每一行。有什么问题?

But instead there is one extra * on every line. What is the problem?

非常感谢!

推荐答案

神秘有一个解决方案,你打印两个星号迭代的方式。使用山坳在你的例子也使事情不仅仅是更混乱I <标识符/ code>和Ĵ以来,特别是外环实际上是你的当前行。

Mystical has a solution to the way you're printing two asterisks an iteration. Using the identifiers row and col in your example also makes things more confusing than just i and j, especially since the outer loop is actually your current row.

你的烂摊子另一种方法是(我希望这不是功课,因为它没有标记为此类):

An alternative to your mess is (I'm hoping this isn't homework since it's not tagged as such):

int main(void)
{
   int size = 5;
   int i, j;

   for (i = size; i > 0; i--) {

      for (j = i; j < size; j++)
         putchar(' ');

      for (j = 0; j < i*2 - 1; j++)
         putchar('*');

      putchar('\n');
   }

   return 0;
}

您也可以把我* 2 - 1 中,以便它不是在循环的每次迭代计算的(除非编译器看到的,你不修改变量 I )。

You could also put i*2 - 1 in a variable so that it's not calculated at each iteration of the loop (unless the compiler sees that you're not modifying i).

这篇关于输出看起来像在C三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆