【问题标题】:C - Need to print a pyramid with #'s when the user inputs a height [duplicate]C-当用户输入高度时,需要用#打印一个金字塔[重复]
【发布时间】:2014-04-26 15:57:53
【问题描述】:

我需要让用户输入一个高度值,如果它高于 23 或小于 0,它应该再次询问。然后它应该打印一个金字塔,有点像马里奥兄弟游戏结束时的楼梯(右侧有 2 个标签,参见示例)。问题是代码运行并且不打印任何#,代码刚刚结束。这是一个在线课程,所以请不要只发布代码,如果您要发布完整代码,请说明。

金字塔示例:https://www.dropbox.com/s/4fyg2ls0eml7asi/Screenshot%20from%202014-03-20%2002%3A15%3A08.png

我遵循的流程图:http://i.imgur.com/otuDOtK.png

#include <stdio.h>
//#include "cs50.h"

int main(void){
    //int h = 0;
    printf("Enter height between 0 and 23: ");
    int h = scanf("%d", &h);
    while (h < 0 || h > 23){
        printf("Retry: ");
        h = scanf("%d", &h);
    }
    int l = 1;
    if (h == 0){
        //printf("ln21\n"); //Debug
        return;
    }
    int s = h - 1;
    int b = l + 1;
    if (s == 0){
        if (b == 0){
            printf("\n");
    h = h - 1;
    l = l + 1;
    if (h == 0){
        return;
    }
        }
    }
    else{
    printf("#");
    b = b - 1;
    }
}

【问题讨论】:

标签: c input user-input cs50


【解决方案1】:
#include <stdio.h>

int main(){
    int height = 8;//Number of repetitions of basic.
    int max_width = height + 1;//Number of block(#) in the largest display
    int i, j, w;
    for(i = 0; i < height; ++i){
        printf("%*s", max_width -(i+2), "");//Print a space in front of the block
        for(w = 0; w < i+2; ++w){
            printf("#");//display a block of each floor
        }
        printf("\n");
    }
    printf("\n");
    return 0;
}

#include <stdio.h>
#include <string.h>

int main(){
    int height = 8;
    int max_width = height + 1;
    char wall[max_width + 1];
    int i;
    memset(wall, '#', sizeof(wall)-1);// make a block of maximum.
    wall[sizeof(wall)-1] = '\0';
    for(i = 0; i < height; ++i){
        printf("%*.*s\n", max_width, i+2, wall);//View of block size and the required blank
    }
    return 0;
}

【讨论】:

  • 这行得通。但你根本没有解释。
  • 如何设置“int height = scanf(不知道放什么);”
  • @SeanBehan 你需要去查找scanf。它不会返回您认为的结果。
  • @CareyGregory 是的,我就是这么做的。大声笑我觉得很愚蠢。该代码现在有效。我会更新问题代码。
  • 刚刚意识到你不需要 j 在第一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多