1

Just a program here that subtracts a number from another number. I'm getting differences of -23882489428948248829...etc...can you tell why?

#include <stdio.h>

double minus(double a, double b) { // set up minus function
    double difference = a - b;
    return difference;
}

int main() //begin program
{
    double a; //declare variables in this scope 
    double b;

    printf("Enter the first number:\n");
    scanf_s("%f", &a); //get a from user

    printf("Enter the second number:\n");
    scanf_s("%f", &b); //get b from user

    printf("The difference is %f\n", minus(a,b)); //print results
    return 0;
}
kits
  • 609
  • 6
  • 20
  • 7
    use `"%lf"` for `double` in `scanf` – BLUEPIXY Dec 23 '14 at 01:24
  • @BLUEPIXY But I remember old days of Turbo C, `%f` was ok for both float and double? But in Visual Studio it behaves strange. – Pranit Kothari Dec 23 '14 at 01:27
  • Why people downvote without comment? – Pranit Kothari Dec 23 '14 at 01:28
  • You will get your exact answer here - http://stackoverflow.com/q/210590/744616 – Pranit Kothari Dec 23 '14 at 01:30
  • the printf format "%f" is not correct for a double value, rather use "%lf" – user3629249 Dec 23 '14 at 01:47
  • @user3629249 `%f` and `%lf` of `printf` are both valid. – BLUEPIXY Dec 23 '14 at 01:49
  • regarding function scanf() 1) the returned value from scanf() should always be checked to assure the operation/conversion was successful. 2) the format string needs to skip over any 'left over' white space in the input stream. Therefore, the format string should be: " %lf" <-- notice the leading ' ' (space) – user3629249 Dec 23 '14 at 01:51
  • @PranitKothari I do not know how was the Turbo C. But `%lf` of scanf is already enabled on the C89. – BLUEPIXY Dec 23 '14 at 01:52
  • 1
    @user3629249 most scanf specifiers, including `%lf`, already skip leading whitespace. your suggested space is redundant – M.M Dec 23 '14 at 01:59
  • 2
    @PranitKothari: For `printf`, `float` arguments are promoted to `double`, so `%f` is valid for both. For `scanf`, the argument is a pointer, and there is no promotion, so two different format strings are needed: `%f` for `float*`, `%lf` for `double*`. I'm skeptical that this was any different under Turbo C (unless `float` and `double` had the same size and representation, but that seems unlikely). – Keith Thompson Dec 23 '14 at 02:10
  • @PranitKothari: In days of Turbo C, `"%f"` was ok for both float and double for `printf()`. Code needed `"%lf"` for `double` (actually `double*`) and `"%f"` for `float` for `scanf()`. – chux - Reinstate Monica Dec 23 '14 at 03:20

1 Answers1

1

For double a %lf should be used instead of %f because in scanf_s/scanf when you pass double with %f, it will be indicated for 4 byte entity, and double is of 8 bytes (in Visual Studio).

Sizes may differ on compiler implementation, but mostly above mentioned reason stay relevant.

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137