首页 > 解决方案 > 将“c99”循环转换为常规内容

问题描述

故事:我试图将 c99 脚本转换为常规 gcc。

问题:输出为空。

预期输出:3,2,1

length是数组中元素的数量。

更新:该脚本旨在按降序对数组元素进行排序。

编码:

#include <stdio.h>

int main() {

    int arr[] = { 1,2,3 };
    int temp = 0;
    int length = sizeof(arr) / sizeof(arr[0]);
    int i = 0;
    int j = i + 1;

    for (i < length; i++;) {
        for (j < length; j++;) {
            if (arr[i] < arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }

    int y = 0;

    for (y < length; y++;) {
        printf("%d ", arr[y]);
    }

    return 0;
}

标签: c

解决方案


您的 for 循环语法问题所在。

这是编写循环的正确方法。

int i, j;
for (i = 0; i < length; ++i)         // for (initialisation; test condition; operation)
{
    for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of 
                                     // the outer loop.  That's what makes the bubble sort work.
    {
         /* test and swap if needed */
    }
}

for (i = 0; i < length; ++i)  // note that i is reset to zero, so we can scan the array from 
                              // a known position (the top) to bottom.
{
    /* printout */
}

推荐阅读