简体   繁体   English

函数的返回值不正确

[英]Return value of function is incorrect

I'm writing a program that checks an array to see if 3 of the elements in that array are the same value. 我正在编写一个检查数组的程序,以查看该数组中的3个元素是否具有相同的值。 The program simply outputs "Yes, something is the same 3 times" or "No, nothing repeats 3 times." 该程序仅输出“是,某事物相同3次”或“否,没有重复3次”。 The program assumes all elements are greater than zero, and that there's only one set that could potentially repeat. 该程序假定所有元素都大于零,并且只有一组可能重复。 For some reason the return value from my function returns either 0 or -2, so the program always defaults to "No, there's no repeating value". 由于某种原因,我函数的返回值返回0或-2,因此程序始终默认为“否,没有重复值”。 We were told to use 3 nested for loops as well. 有人告诉我们也要使用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;
}

There is no return value for if the loop fails to find a repeating value. 如果循环未能找到重复值,则没有返回值。

At the end of the function you should return the value found or return an error value. 在函数末尾,您应该返回找到的值或返回错误值。

If you wish to follow the single exit principle, then a value should be assigned to the error code at the beginning of the function then changed if a repeated value is found. 如果希望遵循单出口原则,则应在函数的开头为错误代码分配一个值,如果发现重复的值,则应将其更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM