c - 将“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;
}
解决方案
您的 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 */
}
推荐阅读
- tensorflow - 仅使用神经网络的寻路
- python - Python AsyncJsonWebSocketConsumer 问题
- python - 如何将数据重新采样为“奇数(而不是偶数)”2 小时时间范围?
- java - 想在我的数据库中返回一个 rs.getInt() 值
- bash - symfony server:start 命令抛出错误
- woocommerce - 无法按供应商添加 woocommerce 订单过滤器
- r - 在直方图的背景中添加图像
- java - 无法在 Android 上获得写入权限
- sql - 如何避免多次加入同一张表?
- php - 如何将带有 arc2 的新个人添加到我的 owl 文件中?