c - C 中的循环不能正确递增

标签 c for-loop while-loop

你好,我是 C 语言新手,我正在使用 c99 进行编译,我只是在制作一个使用 * 打印不同形状的程序。

我在制作对角线时遇到问题,这是我在 switch 语句内使用 while 循环和嵌套 for 循环的代码。

如果我告诉它会有 5 *,我会得到 3 作为返回,如果我给它数字 7,我会得到 4。间距工作正常,但它没有完成循环。

任何帮助都会很棒!

case 'd':
    printf("Size: ");
    scanf("%d", &num);
    index =0;
    while (index<=num){
// makes spaces
    for (int i=0; i<num-1; i++){
            printf(" ");
    }
    printf("*");
    printf("\n");
    num--;
    index++;
    }             
    break;

输入 尺寸:5 输出: * * *

最佳答案

尝试下面的代码..应该为你绘制对角线。

变化:

  1. while (index<num){ While condition edited.
  2. for (int i=index-1; i >= 0; i--) for edited from index to 0.
  3. num--; not required.
while (index<num){
        // makes spaces
        for (int i=index-1; i >= 0; i--)
        {
            printf(" ");
        }
        printf("*");
        printf("\n");
        //num--;
        index++;
    } 

关于c - C 中的循环不能正确递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293258/

相关文章:

c - 由于 cscanf() 和 cprintf() ,程序无法编译

java - 当标志在不同线程中更改时循环不会结束

c++ - SDL 中没有可用的视频设备

visual-studio - 可以使用 ReSharper 将 'foreach' 转换为 'for' 循环,反之亦然?

python - 如何从文件夹内的 n 个 csv 文件导入数据?

Java:字符串更改,因此 for 循环中所有项目的名称都更改

bash - 从 while read 行运行函数

python - 退出 for 循环

c - "realloc(): invalid next size"多次成功运行后

c - 使用 qsort 对 long long int 数组进行排序不适用于大型 nos