C:使用数组,总是给我错误的输出

标签 c

我一整天都在努力解决这个问题,除了中间结果之外,我得到的输出都是正确的。如果有人能帮助我那就太好了。我得到的输出是 id[A] 而不是 id[C],看起来在循环中 A 的 ID 被传送到 C。

    int firstA=0, firstS=0, secondS=0, firstC=0, secondC=0;

    for (row=0; row<totalSize; row++) {

        if (category[row]=='A' && ranking[firstA] < ranking[row]) {
            firstA = row;

        }

        if (category[row]=='C' && ranking[firstC] < ranking[row]) {
            secondC = firstC;
            firstC = row;
        }
        else if (category[row]=='C' && ranking[secondC] < ranking[row]) {
            secondC = row;
        }

        if (category[row]=='S' && ranking[firstS] < ranking[row]) {
            secondS = firstS;
            firstS = row;
        }
        else if (category[row]=='S' && ranking[secondS] < ranking[row]) {
            secondS = row;
        }


    }

    printf("A : %d %.2lf \n", id[firstA], ranking[firstA]);
    printf("C : %d %.2lf \n", id[firstC], ranking[firstC]);
    printf("C : %d %.2lf \n", id[secondC], ranking[secondC]);
    printf("S : %d %.2lf \n", id[firstS], ranking[firstS]);
    printf("S : %d %.2lf \n", id[secondS], ranking[secondS]);

    return 0;
}

输入文件

10
14 A 447 252 68 34 978
2 C 230 299 597 180 9
27 A 318 220 97 28 1317
32 C 563 450 547 112 28
8 C 669 260 200 36 171
11 S 179 45 1342 732 174
19 S 74 249 861 1165  6 
21 A 757 240 97 119 2032
15 S 275 177 588 577 52
6 C 886 401 327 109 48

预期输出

A: 21 1171.00
C: 6 696.70
C: 32 578.00
S: 11 1094.20
S: 19 1046.50

问题就在这里,我明白了

A : 21 1171.00
C : 6 696.70
C : 14 601.10
S : 11 1094.20
S : 19 1046.50

中间的 C 带有其中一个 A 的 ID。我似乎无法弄清楚我的循环出了什么问题。任何帮助将不胜感激!

最佳答案

第二个S 被初始化为第0 行,即类别“A”。该行的排名小于预期的 secondaryS 行,因此 secondaryS 保持为 0。您需要执行一些操作,以便初始值始终分配给正确的类别,如下所示

   int firstA=-1, firstS=-1, secondS=-1, firstC=-1, secondC=-1;

   for (row=0; row<totalSize; row++) {

       if (category[row]=='A' && (firstA == -1 || ranking[firstA] < ranking[row])) {
           firstA = row;
       }

       if (category[row]=='C' && (firstC == -1 || ranking[firstC] < ranking[row])) {
           secondC = firstC;
           firstC = row;
       }
       else if (category[row]=='C' && (secondC == -1 || ranking[secondC] < ranking[row])) {
           secondC = row;
       }

       if (category[row]=='S' && (firstS == -1 || ranking[firstS] < ranking[row])) {
           secondS = firstS;
           firstS = row;
       }
       else if (category[row]=='S' && (secondS == -1 || ranking[secondS] < ranking[row])) {
           secondS = row;
       }


   }

由于所有初始索引都是 -1,因此只要您看到相应类别的一行,它们就会被分配。将索引初始化为 -1 可能很危险,但这是安全的,因为 C 应该在看到例如以下情况时停止评估条件语句: firstA == -1,并且由于短路评估,永远不会评估排名[-1]。

关于C:使用数组,总是给我错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43012175/

相关文章:

c - 预处理器宏如何工作?

C 结构问题

c - 将级别顺序插入到二叉树中?

C 中的常量值

c - 使用字符串索引数组 (C)

c - 使用带有 EVP 接口(interface)的 AES/GCM 的段错误

c - 为什么 `fseek(..., 0, SEEK_CUR)` 在 Windows 上失败?

c++ - C中的静态变量初始化

c - 调用返回 int 的函数后,在非 void 函数中调用 return 的结果是什么?

按下按钮更改窗口标题不起作用