2

The code below compiles alright:

#include <stdio.h>

double add(double summand1, double summand2)
{
    double sum;
    sum = summand1+summand2;
    return sum;
}

double subtract(double minuend, double subtrahend)
{
    double diff;
    diff = minuend-subtrahend;
    return diff;
}

int main()
{
    double a,b,c,d;
    printf("Enter Operand 1:\n");
    scanf("%d",&a);
    printf("Enter Operand 2:\n");
    scanf("%d",&b);
    // Add
    c = add(a,b);

    // Subtract
    d = subtract(a,b);

    printf("Sum: %.3f\n", c);
    printf("Difference: %.3f\n", d);

    return 0;
}

However, when entering 5 and 5 the result is 0.000 (wrong) and 0.000 (expected). When entering a decimal number (e.g. 2.5), the second prompt is skipped altogether and two random numbers are printed for sum and difference. The problem must be with the data types double and float, which I seem to be using incorrectly.

compor
  • 2,239
  • 1
  • 19
  • 29
Xuttuh
  • 29
  • 4
  • 4
    Different data types have different format specifiers for `scanf`. You are using wrong ones. – Eugene Sh. Aug 22 '18 at 14:19
  • Use `%lf` to read floating-point types in `scanf`. – John Bode Aug 22 '18 at 14:24
  • @JohnBode `%lf` is for `double`. Each floating point type has its own specifier – M.M Aug 22 '18 at 23:20
  • [C - Scanf not changing value of double](https://stackoverflow.com/q/46620751/995714), [Reading in double values with scanf in c](https://stackoverflow.com/q/13730188/995714) – phuclv Aug 23 '18 at 02:08

1 Answers1

5

In your scanf()you used the format specifier %dwhich is used for integers. As you declared your whole variables as doubles use %lf (floating point) instead. I tried the code and with the correct specifier, the Code works.

Alan
  • 589
  • 5
  • 29