【问题标题】:Nested for/while loops for repetition in C [closed]在 C 中用于重复的嵌套 for/while 循环 [关闭]
【发布时间】:2020-11-11 06:39:49
【问题描述】:

我的目标是打印一个具有用户定义变量的宽度/高度的立方体。为什么嵌套在while循环中的for循环可以做到这一点,而while循环中的while循环(具有不同的计数变量)却不能?

【问题讨论】:

  • y 在哪里重置为0?也许在x++; 之后添加y=0;?对于单个字符的输出,使用putchar ('#');putchar ('\n'); 您需要从x 循环中删除printf ("#")
  • 如果您将代码作为文本编辑到您的问题中,您的代码将占用更少的空间,更易于阅读,并且对屏幕阅读器友好。
  • 看不到问题,我看不到图片,为什么我们接受这种问题?

标签: c for-loop while-loop


【解决方案1】:

对您的问题的简短回答,第二个示例不打印该块,因为您在输出一行字符后未能重置y = 0;。如果您与使用for 循环进行比较,则每次调用内部循环都以y == 0 开头。在您的 while 循环实现中,y 永远不会重置。

您的代码的完整实现,必要时重置y 将是:

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

void block (void) {
    
    int w = get_int ("What would you like the width/height to be: "),
        x = 0,
        y = 0;
    
    while (x++ < w) {
        while (y++ < w)
            putchar ('#');
        putchar ('\n');
        y = 0;
    }
}

int main (void) {
    
    block();
}

(注意:您可以根据需要将xy 的增量移出循环条件。还要注意'#' 的输出已从@987654331 中删除@-loop 和 putchar() 已用于输出单个字符,而不是调用可变参数 printf() -- 尽管一个好的编译器会为你做这个切换)

使用/输出示例

几个例子:

$ ./bin/square_while_cs50
What would you like the width/height to be: 5
#####
#####
#####
#####
#####

$ ./bin/square_while_cs50
What would you like the width/height to be: 10
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########

注意:如果您真的想让事物看起来“方形”,请将putchar ('#'); 替换为字符串" #"fputs (" #", stdout);

另外,请不要发布代码图片,而是将代码复制并粘贴到问题中,以 4 个空格缩进,使其格式为代码(或上下使用 3 个反引号)

如果您有任何问题,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2023-03-02
    • 2020-10-09
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多