函数返回值不正确

时间:2018-02-12 00:53:12

标签: c arrays function debugging return

我正在编写一个检查数组的程序,以查看该数组中的3个元素是否相同。该程序只输出"是的,有些东西是相同的3次"或"不,没有重复3次。"该程序假设所有元素都大于零,并且只有一个元素可能会重复。 由于某种原因,我函数的返回值返回0或-2,因此程序始终默认为"不,没有重复值"。我们被告知也使用3个嵌套for循环。

#include <stdio.h>
#include <stdlib.h>
int same_three(int a[], int n) {
    int i = 0;
    int j = 0;
    int k = 0;
    n = 0;
    int repeated = 0;

    for(i = 0; i < n-2; i++) {
        repeated = a[i];

        for(j = i + 1; j < n-1; j++)
            if(repeated == a[j]) {
                repeated = a[j];
                for(k = j + 1; k < n; k++)
                    if(repeated == a[k]) {
                            return repeated;
                    }
            }
    }
}
int main() {
    int length = 0;
    int i = 0;
    int n = 0;
    int repeated = 0;

    printf("Enter the length of the array: "); //user inputs array length
    scanf("%d", &length);

    int a[length];
    printf("Enter the elements of the array: "); //user inputs individual   elements
    for (i = 0; i < length; i++) {
        scanf("%d", &a[i]);
    }
    repeated = same_three(a, i);
    printf("%d", repeated); //check value for repeated, returning as 0 or negative
    if(repeated > 0){
        printf("There are 3 numbers with the same value in the array: %d", repeated);
    }
    else {
        printf("The array does not contain three numbers with the same value.");
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果循环无法找到重复值,则没有返回值。

在函数结束时,您应返回找到的值或返回错误值。

如果您希望遵循单一退出原则,则应在函数开头为错误代码分配值,如果找到重复值则更改。

相关问题