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

时间:2015-04-17 02:34:35

标签: c arrays

我有以下程序 -

#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

1 个答案:

答案 0 :(得分:3)

据我所知,主要问题是您尚未初始化arrayBlank并正在使用它:

arrayBlank[temp]++;

这肯定是未定义行为的原因。我会使用

arrayBlank初始化为零
int arrayBlank[100] = {0};

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

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

使用:

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

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