【问题标题】:sorting struct in C cant show output result in VS2017, but show in CodeBlocksC中的排序结构无法在VS2017中显示输出结果,但在CodeBlocks中显示
【发布时间】:2017-05-20 14:37:06
【问题描述】:

所以基本上我想对文件中的数字进行排序。所以我先读了

for (int i = 0; i < count; i++) {
        fscanf(read_file, "%d %s %d %s\n", &custid_temp[i].id, custid_temp[i].name, &custid_temp[i].reward_point, custid_temp[i].promo);
        printf("%d %s %d %s\n", custid_temp[i].id, custid_temp[i].name, custid_temp[i].reward_point, custid_temp[i].promo);
    }

文件由以下内容组成:

1 Test 200 WELCOME2017
2 James 700 WELCOME2017

看是文件中的点,200和700,我想按升序(从大到小)排序变成这样:

2 James 700 WELCOME2017
1 Test 200 WELCOME2017

所以我将使用这个函数对文件进行排序:

for (int i = 0; i<count+1; i++)
    {
        for (int j = 0; j<count - i; j++)
        { 
            if (custid[j].reward_point <custid[j + 1].reward_point)
            {
                struct customer temp_sort = custid[j];
                custid[j] = custid[j + 1];
                custid[j + 1] = temp_sort;
            }
        }
    }

最后打印更新的结构:

for (int i = 0; i < count; i++) {
        printf("%d %s %d %s\n", custid[i].id, custid[i].name, custid[i].reward_point, custid[i].promo);
    }

结果是这样的(VS2017):

1 Test 200 WELCOME2017
2 James 700 WELCOME2017
0  0
0  0

结果是这个(代码块):

1 Test 200 WELCOME2017
2 James 700 WELCOME2017
2 James 700 WELCOME2017
1 Test 200 WELCOME2017

Process returned 2 (0x2)   execution time : 0.015 s
Press any key to continue.

即使使用相同的代码,为什么两个编译器会产生 2 个不同的结果,是否有任何解决方案可以在 VS2017 上运行?

无论如何,感谢您的时间。

【问题讨论】:

  • 调试器是你的朋友。
  • custid[j + 1] 出现越界。
  • Visual Studio 和 CodeBlock 是 IDE,而不是编译器。 Visual Studio 使用 Microsoft 的 cl.exe 或 Clang 的修改版本。 CodeBlocks 可以支持广泛的编译器 AFAIK。
  • @BLUEPIXY ,但如果我将custid[j + 1] 更改为custid[j]custid[j - 1],它会产生这个。 1 Test 200 WELCOME2017 2 James 700 WELCOME2017 1 Test 200 WELCOME2017 2 James 700 WELCOME2017 Process returned 2 (0x2) execution time : 0.010 s Press any key to continue. 这意味着它不再排序了
  • 你使用custid_temp作为阅读。但是您使用custid 作为排序。

标签: c sorting struct


【解决方案1】:

尝试更一般地处理排序问题。通过实现一个比较器函数来定义一个顺序,以便能够决定一个元素是否小于、等于或大于另一个元素。定义一个函数接口,它接受你的数组和一个指向比较器的函数指针(将数组的两个元素作为参数并返回 -1、0 或 1 以表示更小、等于或更大)。

最后使用快速排序或其他众所周知的算法来执行实际排序。确定您是否要求订单是总计的 - 如果您的排序算法应该返回确定性结果,这是一个理想的属性。

更具体地说,我鼓励使用 C 标准库中的qsort。它有很好的记录:http://www.gnu.org/software/libc/manual/html_node/Search_002fSort-Example.html

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2020-04-20
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多