簡體   English   中英

在C語言中,迭代函數沒有給出正確的輸出,該輸出應該是不是總和(來自用戶輸入的數據)或數據數組中的數字?

[英]In C, iterative function is not giving the right output which is supposed to be a number not in sum(from data entered by user) or in data array?

我正在做作業。 我的任務是:編寫一個程序,以查找未出現在數組中並且不能由數組中兩個數字之和形成的最小正整數。
int issumof2(int data [],int大小,int數)
int inarray(int data [],int size,int number) (大小是數組中元素的數量,數據是從用戶那里獲取的)
我真的對如何解決這個問題感到困惑。 我不知道如何同時使用這兩個函數來查找數字。 在這個p

#include <stdio.h>
//function declaration
int issumof2(int data[], int size, int number);
int inarray(int data[], int size, int number);
int i, data[7], size = 7, sum, n=0 number=0;

int main()
{
    printf("Enter 7 numbers ");
    for (i = 0; i < size; i++)
        scanf("%d", &data[i]);
    //function call
    inarray(data, size, number);
    issumof2(data, size,number);
    printf("Number is %d\n", issumof2(data, size,number));//this is most likely wrong
    return 0;
}
int issumof2(int data[], int size, int number)//add all combinations of data
{
    inarray(data, size, number); //calling inarray to check that number isn't in data
    {
        for (j = i + 1; j < size; j++)//professor told me to use j<i but it doesn't work for some reason
        {
            sum = data[i] + data[j];//gets the sum
            if (number != sum && number != data[i])
            {
                number = data[i]+1+number; 
                number++;
                data[i]++;//moving on to the next data
            }

        }

    }

    return number;//this is also returning number??
}
int inarray(int data[], int size, int number)//check if number is in array
{
    if (n <=size)
    {
        if (number != data[i])
            number = data[i] + 1 + n;
            n++;
            data[i]++;//moving on to the next data
    }   
    return number;//this is returning number
}

expected output:
Enter 7 numbers
1 2 2 3 4 3 1
Smallest positive Integer = 9

您的main()函數的結構應如下所示:

int main()
{
    printf("Enter 7 numbers ");
    for (i = 0; i < size; i++)
        scanf("%d", &data[i]);
    while (inarray(data, size, number) || issumof2(data, size, number)) {
        number++;
    }
    printf("Number is %d\n", number);
    return 0;
}

然后,您需要編寫inarray()issumof2()函數,以便在給定數字滿足條件的情況下返回true否則返回false 他們不應該自己搜索號碼。 我把這作為練習留給您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM