سؤال

I'm having an issue where my functions seems to be only returning one. I thought that I was returning the functions correctly but it seems that I am not.

char goAgain()
{
char ch;
do
{
    printf("Would you like to go again? ");
    ch = getchar();
    while(fgetc(stdin) != '\n');
}while(ch != 'n' || 'y');

return ch;
}


double findMedian(int array[], int length)
{
int mid;
double median, medianLeft, medianRight;
if(length % 2 == 0)
{
    mid = length / 2;
//      medianLeft = array[mid];
//      medianRight = array[mid + 1];
}
else
{
    mid = length / 2;
    median = array[mid];
}

return median;
}

this is how I am calling the median

double mean = findMedian(array, length);

why is it only giving me a one in my return. also when i try to repeat the goAgain I don't get the correct ch to be returned either.

option = goAgain();

things are a lot different in the c world compared to the java world.

do
{
    int num = menu();

    if(num == 1)
        fillArray(array, size);
    else if(num == 2)
    {
        int newSize = readNum();
        fillArray(array, newSize);
    }
    else if(num == 3)
    {
        int length = size;
        sortArray(array);
        double mean = findMean(array, length);
        double median = findMedian(array, length);
        printResults(mean, median);
    }
    else
    {
        printf("Please enter a valid number\n");
        num = menu();
    }

    option = goAgain();
}while(option == 'y');
هل كانت مفيدة؟

المحلول

This condition:

(ch != 'n' || 'y')

Is probably not doing what you want. It is interpreted by the compiler like this:

((ch != 'n') || 'y')

Which means "if ch is not the character n OR if the character y". If your machine uses ASCII, then y has the value 121. What happens if you do:

((whatever) || 121)

For the boolean OR operator (||) the value 0 represents false and every other value represents true. And what do you get when at least least of the operands of a boolean OR operation are true? You get true.

So, your condition is, essentially, the same as simply writing

 (1)

It looks like you want:

(ch != 'n' && ch != 'y');

نصائح أخرى

When this:

if(length % 2 == 0)

... evaluates true, you don't calculate a value for median, yet still return it.

(And then add in whatever becomes from Carl's answer, which is dealing with the "and also" part of your question!)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top