【问题标题】:Unable to control a variable in a loop无法控制循环中的变量
【发布时间】:2022-01-18 10:41:18
【问题描述】:

我似乎无法理解为什么这部分代码不起作用,尽管它非常简单。程序应该这样做,1.输入:要求用户插入一个数字(值存储在高度中),2.输出:然后程序将返回“”(空格),每行递减。

这是我想要的结果示例:(我使用 F 而不是空格)

输入:4

输出:

FFFF
FFF
FF
F

这就是我得到的:

输入:4

输出:

FFFF
FFFF
FFFF
FFFF

        for (int r = 0; r <= height; r++)        // first loop, does the columns
      { int space = height;

        space -= 1;                             // decrements space value by 1 for each loop

        while (space != 0)                      // list out the correct spaces in each row
        {   
                                  
            printf (" ");
            space--;    
        }

【问题讨论】:

  • 首先请尝试创建一个合适的minimal reproducible example 来展示给我们。其次,我建议您学习一些常见的调试技术,例如rubber duck debugging,并使用实际的调试器逐语句逐句执行代码,同时监控变量及其值。这应该可以帮助您了解会发生什么。
  • 您好,感谢朋友的反馈!是的,我也同意我的问题是徒劳的,我真的认为添加示例会使我的问题更具可读性,下次我会做得更好。感谢您的提示,我一定会了解有关调试的更多信息!

标签: c loops for-loop while-loop


【解决方案1】:

在外循环的每次迭代中,您都将 space 重新初始化为 height,因此每次迭代都会得到相同的输出。

更简单的方法是使用循环变量作为列数并对其进行迭代向后

for (int r = height; r > 0 ; r--)
{
    for (int space = 0; space < r; ++space)
    {
        printf("F");
    }
    printf("\n");
}

【讨论】:

    【解决方案2】:

    在for循环中

        for (int r = 0; r <= height; r++)        // first loop, does the columns
      { int space = height;
    
        space -= 1;                             // decrements space value by 1 for each loop
    
        while (space != 0)                      // list out the correct spaces in each row
        {   
                                  
            printf (" ");
            space--;    
        }
    

    变量空间始终设置为相同的值height - 1

         int space = height;
    
        space -= 1;
    

    您可以通过以下方式输出您显示的模式

    for ( ; 0 < height; --height )
    {
        for ( int i = 0; i < height; i++ )
        {
            putchar( 'F' );
        }
    
        putchar( '\n' );
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多