-2

For my school project we are required to do math with doubles. My current code produces some unexpected results.

/* Hello World program */

#include<stdio.h>

int main()
{

double result = 0.0;
double x;
x = 10.0;

result = x + 10.0;

printf("%d", result);

return 0;

}

Upon running, this code prints: "-1267258024"

I don't understand why this happens? Why does the code not print 20.0?

Thanks!

EDIT: I'm so dumb. %d is for floats. Thank you!

1 Answers1

1

The line

printf("%d", result);

indicates that you want to print an integer.

You probably want

printf("%f", result);

There are also things like %lf (acts the same as %f) and %Lf (works for long doubles) which you can read about on this answer.

A complete list of formatting options can be found here.

Richard
  • 56,349
  • 34
  • 180
  • 251