gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:59:06 25 4
gpt4 key购买 nike

我一整天都在努力解决这个问题,除了中间结果之外,我得到的输出都是正确的。如果有人能帮助我那就太好了。我得到的输出是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com