gpt4 book ai didi

C 程序输出在不同机器上有所不同

转载 作者:行者123 更新时间:2023-11-30 18:39:30 24 4
gpt4 key购买 nike

我有以下程序 -

#include <stdio.h>

int main() {
int counter = 0;

int responses[28];
printf("Enter student section values: \n");
while(counter != 27) {
scanf("%d", &responses[counter]);
counter++;
}

int i = 0;
int arrayBlank[100];
int temp = 0;
int past = 0;
int present = 0;
int future = 0;
int flag = 0;
for(i = 0; i < counter; i++) {
if((i - 1) < 0 || (i + 1 >= counter)) {
;
}
else {
past = responses[i - 1];
present = responses[i];
future = responses[i + 1];
if(present == past || present == future) {
temp = present;
flag=1;
arrayBlank[temp]++;
} else {
arrayBlank[i] = 0;
}
}
}

if(flag == 0) {
printf("\nThe order input does not assign any adjacent students from the same team\n");
return 0;
} else {
int chut[28];
int index = 0;
for(i = 0; i < 27; i++) {
index = responses[i];
chut[index]++;
}

for(i = 0; i < 27; i++) {
if(chut[i] <= 0 || chut[i] > 26) {
chut[i] = 0;
}
}
printf("\nThe order input currently assigns adjacent students from the same team.\n");
printf("\nTeam Students\n");
for(i = 0; i < 27; i++) {
if(chut[i] != 0) {
printf("%d %d\n", i, chut[i]);
}
}
//1 2 3 3 4 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8

}
return 0;
}

基本上,对于给定的数字范围,它检查给定条目中是否有任何特定数字具有与该数字相同的相邻值。如果有,它只会打印特定元素在给定数字范围内出现的次数。

示例 - 对于数字列表

1 2 3 3 4 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8

程序的执行就像 -

Enter student section values: 1 2 3 3 5 6 7 8 9 1 2 3 4 5 5 7 8 9 1 2 3 4 5 6 7 8 8

The order input currently assigns adjacent students from the same team.

Team Students
1 3
2 3
3 4
4 2
5 4
6 2
7 3
8 4
9 2

问题:我无法弄清楚不同机器上输出不同的原因以及如何解决该问题。例如,在使用 XCode 运行程序的 Macbook 上,输出是正确的,尽管当我在使用 gcc 编译器(Big Endian 机器)的 Linux 机器上运行它时,输出是不同的。我不确定 Endianess 是否与输出不同有关。

在 Little Endian Linux 机器上 -

enter image description here

在 Big Endian Linux 机器上 -

enter image description here

在在线编译器上 ( Tutorial's Point ) -

enter image description here

最佳答案

据我所知,主要问题是您尚未初始化 arrayBlank 并将其用于:

arrayBlank[temp]++;

这肯定是导致未定义行为的原因。我将使用 arrayBlank 初始化为零

int arrayBlank[100] = {0};

第二个问题是读取数据的循环计数器不正确。而不是:

while(counter != 27) {
scanf("%d", &responses[counter]);

用途:

while(counter != 28) {
scanf("%d", &responses[counter]);

当您使用 counter != 27 停止时,可以使用索引 27 访问的 responses 的最后一个元素永远不会被读取来自文件。

关于C 程序输出在不同机器上有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689253/

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