D
D
dandropov952018-09-15 19:44:27
C++ / C#
dandropov95, 2018-09-15 19:44:27

Why is the incorrect value of a real number displayed?

Why is it that if you read a number as a long double, then the result is normal, but if you read it as just a double, then the output is not what you would like?
input 2 => output 8.000000 (%lf)
input 2 => output -79298408094324 ... .000000 (%f)

#include <stdio.h>
#include <conio.h>

double cube(double value);

int main(void)
{
  double number;

  scanf("%lf", &number); // %f

  printf("%f", cube(number));

  _getch();

  return 0;
}

double cube(double value)
{
  return value * value * value;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-09-16
@dandropov95

Why if you read a number as a long double, then the result is normal,
input 2 => output 8.000000 (%lf)

because in scanf %lfit's not a long double, it's just a double. %f-- is float and long double is %Lf. See man scanf .
float and double usually differ in representation format, so if you enter a number in the wrong scanf format, then the value will not be what was expected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question