0

I recently (three days ago) began coding in c and i cannot understand why the final scanf is breaking my code.

I checked the syntax and from what i can tell it is correct. I revised the final segment to multiply integers instead of doubles, and it worked. I revised the final segment to multiply floats instead of doubles, and it broke.

int main()
{
    // add two numbers
    int addOne,addTwo,sumOne;
    printf("Please enter two integers: ");
    scanf("%d %d",&addOne,&addTwo);
    sumOne = addOne + addTwo;
    printf("The sum of these two numbers is: %d\n",sumOne);

    // above code works.
    // multiply two decimals

    double decOne,decTwo,mulOne;
    printf("Please enter two decimals: ");
    scanf("%1f %1f",&decOne,&decTwo);
    mulOne = decOne*decTwo;
    printf("the multiplication of the two decimals entered is: %1f \n", mulOne);


    return 0;
}

I expect to be able to intput two decimals and see the product. Instead i can only enter one and it prints out:

Please enter two decimals: 1.2 the multiplication of the two decimals entered is: 241638106882447.190000

saiasI
  • 11
  • 2
  • Should be `%lf`, not `%1f`. (Use a better font). You're reading one character into a memory address you're claiming is a float (not a double). lowercase `L`, not the number one – Tibrogargan Aug 07 '19 at 04:40

2 Answers2

3

Your Problem The issue roots from that you are using %f to write into a double instead of a float. Thus to fix the issue you can either change you format specifier to lf or change the data type of your variables to float

Solution 1

float decOne,decTwo,mulOne;
...
scanf("%1f %1f", &decOne, &decTwo);

or

Solution 2

double decOne,decTwo,mulOne;
...
scanf("%lf %lf", &decOne, &decTwo);
Cabbage Champion
  • 1,193
  • 1
  • 6
  • 21
-1

The format specifier for double data type in C language is %lf. Replace %1f in your scanf to %lf.

Nitish
  • 117
  • 1
  • 7