problem : compilation successful but wrong result

99 Views Asked by At

I'm coding in C on geany a program supposed to display 3 inputed int by descending order, the compilation is successfull but it displays me only the last number and two zero , my teacher told us to use function so... i don't know what's wrong in my code ps : sorry for the identation i prefer checking all of that before to fix this.

#include <stdio.h>
#include <stdlib.h>

int a1,b1;
int a,b,c;
int i,j,k;
int mv;

int maxvalue ( int a1, int b1){
    if (a1 > b1){
        return a1;
    }
    else {
        return b1;
    }
}
    
void order ( int a, int b ,int c){
    int mv = maxvalue( a1, b1);
        
    if (a - mv == 0){
        i = a;
    }
    else if ( b - mv == 0){
        i= b;
    }
    else {
        i = c ;
    }
                    
    printf("%d\n", i);
                
    if (( a < i) && ( a-mv ==0)) {
        j=a;
    }
    else if (( b< i)&&( b - mv ==0 )) {
        j = b; 
    }
    else{
        j = c;
    }

    printf("%d\n",j);

    if (( a < j) && ( a - mv == 0)){
        k=a; 
    }
    else if (( b < j) &&(  b - mv ==0 )) {
        k = b; 
    }
    else{
        k = c;
    }

    printf("%d", k);
}

int main(int argc, char **argv)
{
    a = a1;
    b = b1;
    
    scanf("%d%d%d", &a,&b,&c);
    order(a, b , c);

    return 0;
}
1

There are 1 best solutions below

1
On

One problem as pointed out in the question's comments is that local variables shadow global variables of the same name, and that you should study the concept of SCOPE. As suggested, make variables LOCAL.

Also. in order, int mv = (a1, b1);: You declared, but never explicitly gave values to, a1 & b1. If you examine what a1 and b1 are at the time the maxvalue function is called, you'll see they will contain 0, because in C, a global int will automatically be Zero when declared. (This is not the case for a locally declared variable, in which case the will be filled with meaningless bits until initialized. Because a1 and b1 are not what you expect, mv will not be what you expect, which is likely to foil the logic designed in the remainder of order. Always make sure a local variable is initialized or given a value before you ever use it.

If maxvalue is revised to select the MAX of the first two numbers entered: The Logic that chooses which should be i may fail. Because mv will always be one of a or b, and because one of a - mv ==0 or b - mv would always be true, c would never be assigned to i, and would not be printed first, even if it would be the highest.

In summary,

  • Use Local variables,
  • Initialize any variable before it is used.
  • Re-evaluate the logic of order once you are sure that maxvalue will always return the result you expect for any given input.