c - 在c中交换数组元素

标签 c

希望对你有所帮助。我正在尝试编写一个程序,“给定一个包含 10 个整数的列表(数组),找到绝对值最小的一个并将其位置与最后一个交换并输出新列表。

这是我编写的代码,但它没有交换..

#include stdio.h
#include math.h

int main() {

    int array[10];
    int arraynew[10];
    int absmallest = 0;
    int index = 0;
    int i;
    for (i = 0; i < 10; i++) {
        scanf("%d", &array[i]);
    }
    absmallest = array[0];

    for (i = 0; i < 10; i++) {
        if (abs(array[i]) < absmallest)
            absmallest = array[i];
        index = i;
    }

    int temp;
    temp = array[9];
    array[9] = array[index];
    array[index] = temp;

    for (i = 0; i < 10; i++) {
        printf("%d", array[i]);
    }
}

最佳答案

两个问题:

(1)

    if (abs(array[i]) < absmallest)
        absmallest = array[i];
    index = i;

index = i 超出了 if 语句的范围 - 所以它会在每次迭代中发生,并且不取决于您的条件的结果。

(2)
absmallest = array[0]; 也应该与 abs() 一起使用(如果 array[0] = -5 会发生什么)? for 循环中 abssmallest 的赋值也是如此(absmallest = array[i]; 应该是 absmallest = abs(array[i]);)

关于c - 在c中交换数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11847558/

相关文章:

C printf/read 冲突

c - C 中的乘法问题

c++ - 未定义、未指定和实现定义的行为

c - 通过管道重定向 CMD.exe 输出和输入

无法打印 char 数组的元素

c - 具有条件(三元)表达式的运算符 'sizeof'

c - 需要创建一个返回 int 的函数,该函数基于哪个 char 参数具有更多大写字母

c - 如何比较映射和读取性能

c++ - 错误 : request for member ‘stor_begin’ in ‘v’ , 属于非类类型 ‘igraph_vector_t*’

C 汇编程序函数转换