c - 在 c 中为数组做 while

标签 c arrays loops

我的工作是生成随机数并在数组中排序,然后从大到小显示数字。 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 40
int main()
{
    int array[SIZE];
    int inner, outter, temp, i;

    srand((unsigned)time(NULL));
    //do... while to assign array value
    i=0;
    do{
        array[i] = (int)((rand()%101)+1);
        i++;
    }while(i<SIZE);

    puts("Original array:");


    for(outter=0; outter<SIZE-1;outter++){
            printf("%d\t", array[outter]);
    }

    //bubble sort
    for(outter=0; outter<SIZE-1;outter++){

        for(inner=outter+1; inner<SIZE; inner++ ){

            if(array[outter] > array[inner]){

                 temp = array[outter];
                 array[outter] = array[inner];
                 array[inner] = temp;
            }
        }
    }
    puts("\n");
    puts("Sorted array:");

    printf("i= %d\n",i);
     printf("%d\n", array[39]);
    for(outter=0; outter<SIZE;outter++){
            printf("%d\t", array[outter]);
    }

    puts("\n");
    for(outter=SIZE-1; outter>0;outter--){
            printf("%d\t", array[outter]);
    }
    puts("\n");
    // try using do while loop to display reverse number from biggest to smallest numbers
    do{
        printf("i= %d\n", i-1);
        i--;
    }while(i>-1);
}

当我使用 do while 显示反向数组编号时,我的代码崩溃了。 但是,我显示用于循环数组的“i”值,它显示从 39 到 -1。我不知道为什么我的“i”值设置为 -1,因为我设置了“i>-1”。

最佳答案

TL;DR:将您的 printf 更改为:printf("i= %d\n", i); 或将 while 循环更改为 while(i > 0);。无论哪种方式,它都应该可以解决您的问题。

do while 循环执行大括号中的操作,然后检查条件。我不太理解你的问题,但在我看来它正在打印 -1 因为它先做,然后检查条件。此外,您在 printf 函数中使用了 i - 1(这可能是您最困惑的地方)。

编辑:要更加明确 while 循环,问题是您的条件是 (i > -1)。这意味着当您到达 0 时,您的代码将检查:0 是否大于 -1?。它将返回 true,然后继续打印 -1i = -1。然后它再次到达 while 条件,它看到 -1 不大于 -1,这是代码终止的时间。

关于c - 在 c 中为数组做 while,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801363/

相关文章:

c - gcc 提示 : variable-sized object may not be initialized

C:指针算术 - 它是如何工作的?

c - 如何在 C 中解析带有换行符的字符串?

c - 调用 Seg Fault 以销毁 malloced 结构

c - 如何在函数声明语句中使用二维数组?

c# - 无法将类型为 'System.Object[]' 的对象转换为 'MyObject[]',这是怎么回事?

javascript - 减去数组 - javascript

C++,在数组中找到 3 个最大值,其中这些值之间的差异是参数之一

javascript - 用 `for` 循环替换 `forEach` 循环

arrays - 将数组从某个位置复制到c中的另一个数组