Home > Software design >  Why i cant properly do subtraction in this code can you guys pls help me out
Why i cant properly do subtraction in this code can you guys pls help me out

Time:09-09

#include<stdio.h>
int subtractNumbers(int n1,int n2);
int main(){
    int n1,n2,difference;
    printf("Enter Two Numbers: ");
    scanf("%i%i",&n1,&n2);
    subtractNumbers(n1,n2);
    printf("The Difference is %i", n1,n2);
}
int subtractNumbers(int n1,int n2)
{
    int result;
    result =n1-n2;
    return result;

}

Why this code cannot properly do a subtruction? can you guys please help me.

CodePudding user response:

Have to store the return value in 'difference' variable. (As I guess the 'difference' variable is meant for that)

In case of 'printf("The Difference is %i", n1,n2);' I guess the intention is to print the 'difference'. So change to 'printf("The Difference is %i", difference);'

#include<stdio.h>
int subtractNumbers(int n1,int n2);
int main(){
    int n1,n2,difference;
    printf("Enter Two Numbers: ");
    scanf("%i%i",&n1,&n2);
    difference = subtractNumbers(n1,n2); // stored the returend result
    printf("The Difference is %i", difference); //printing only the result
}
int subtractNumbers(int n1,int n2)
{
    int result;
    result =n1-n2;
    return result;

}

CodePudding user response:

So basically you've mixed up the syntax. It's all right, but when you call your function, it's ok that you return a value, but the in your main you don't read that value.

This fixes it:

#include<stdio.h>
int subtractNumbers(int n1,int n2);
int main(){
    int n1,n2,difference;
    printf("Enter the first number : ");
    scanf("%d",&n1);
    printf("Enter the second number: ");
    scanf("%d", &n2);
    int result = subtractNumbers(n1,n2);
    printf("The Difference is %d", result);
}
int subtractNumbers(int n1,int n2)
{
    int result;
    result = n1-n2;
    return result;

}

CodePudding user response:

Primary problem corrected like other answers, but with more commentary and a few "upgrades"...

#include <stdio.h>

// Please spread things out for your readers. Whitespace is free!

// if function PRECEEDS its use, it is its own "function prototype"
int subtractNumbers( int n1, int n2 )
{
    int result = n1 - n2; // declare and assign together
    return result;
}

int main() {
    printf( "Enter Two Numbers: " );

    // define variables "close" to when they are first used
    int n1, n2;
    // ALWAYS check return codes from system functions. Things go wrong
    if( scanf( "%i%i", &n1, &n2 ) != 2 )
        printf( "Something went wrong\n" );
    else
    {
        // here was where the returned value was not being received. fixed.
        int difference = subtractNumbers( n1, n2 );
        printf( "The Difference is %i", difference );
    }

    return 0; // optional with some compilers
}
  •  Tags:  
  • c
  • Related