0

I'm learning the basics of C right now. I am trying to input data into an array. After some trial and error, I've found that I can do what I need to using a float array as opposed to a double array.

#include <stdio.h>
int main()
{
   float x[4]={2.2,3.3,4.4,5.5};
   scanf("%f",&x[3]);
   printf("%f",x[3]);
   return 0;
}

The user input 3 would result in 3.000000

However in this version:

#include <stdio.h>
int main()
{
   double x[4]={2.2,3.3,4.4,5.5};
   scanf("%f",&x[3]);
   printf("%f",x[3]);
   return 0;
}

The user input 3 would result in 5.500001

Why is this, and how can I properly enter values to/print out the array values?

claivin
  • 11
  • 1
  • 6
    Use `%lf` for double. E.g `scanf("%lf",&x[3]);` – BLUEPIXY Mar 09 '17 at 03:08
  • Thank you for the quick response @BLUEPIXY I've never seen that type before. – claivin Mar 09 '17 at 03:13
  • 6
    To fix this problem **enable compiler warnings** (e.g. `-Wall -Wextra`) when you compile and do not accept code until it compiles without a single warning. Read the warnings -- they tell you exactly what the problem is. Try it on your question code. – David C. Rankin Mar 09 '17 at 03:14
  • 1
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Toby Speight Mar 09 '17 at 13:03

1 Answers1

1

First, you have memory trampling due to use of incorrect format specifiers. First, the corrected example, with less "noise".

#include <stdio.h>

int main(void)
{
   double x = 5.5;
   scanf("%lf", &x);
   printf("%lf", x);
   return 0;
}

Second, you should try and avoid scanf() in general for string parsing, and considering reading on a per-line basis (ie: fgets() or some other mechanism), and then writing a parser. There is a plethora of closed/dupe questions on this site for questions like yours alone. Plus, other things, like newlines being left in the input buffer.

Finally, three good points:

  • David C. Rankin notes: use gcc -Wall -Wextra to catch all compiler warnings. Append -Werror if you want to force yourself not to allow any warnings to get by).
  • Look into learning how to to use gdb to debug programs. It's dead simple: compile with debug symbols and debug mode (and zero optimizations) configured via: gcc -O0 -ggdb, and then gdb my_program_name; joy!).
  • Consider building your programs with stack smash detection enabled (gcc -fstack-protector-strong). It will intentionally "crash" (assert) your programs early if you're doing something very wrong, like what happened in your example. It lets you discover serious memory trampling issues during testing rather than in production. Now isn't a bad time to learn about valgrind, strace, ptrace, helgrind, perf, etc, while you're at it.

Best of luck!

Cloud
  • 18,753
  • 15
  • 79
  • 153