0

I wrote a function to add two double values:

# include <stdio.h>

double addem(double input1, double input2)
{
    double sum ;
    sum = input1 + input2 ;
    return input1 + input2 ;
}

int main(){
    double in1,in2, add = 0 ;
    printf("Enter the numbers\n");
    scanf("%f", &in1);
    scanf("%f", &in2);
    /* Calling function */
    add = addem(in1, in2);
    printf("Sum = %f\n", add);
    
    return 0;
}

However the result always returns a zero:

Enter the numbers
3
3
Sum = 0.000000
genpfault
  • 51,148
  • 11
  • 85
  • 139
kartiks77
  • 48
  • 4
  • 1
    Aside: Don't declare more variables than required. Simply `return input1 + input2`. – Harith Apr 25 '23 at 16:01
  • 3
    A decent compiler should be complaining, and if yours doesn't then enable more warnings. Treat warnings as errors. Mismatching format specifier and argument type leads to *undefined behavior*. – Some programmer dude Apr 25 '23 at 16:02
  • 1
    Does this answer your question? [Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?](https://stackoverflow.com/questions/210590/why-does-scanf-need-lf-for-doubles-when-printf-is-okay-with-just-f) – Raymond Chen Apr 25 '23 at 16:03
  • And *always* check what `scanf` [*returns*](https://en.cppreference.com/w/c/io/fscanf#Return_value). – Some programmer dude Apr 25 '23 at 16:03

1 Answers1

1

Save time and enable all warnings.

double in1,in2, add = 0 ;
....
scanf("%f", &in1);  // Use %lf with double *
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256