Reputation: 901
I have a structure variable health that can be accessed as disk->health, and it is of type double. I am trying to print it as a double and then convert it into an int and print it again.
printf("The disk health in loop is: %lf\n", disk_ptr->health);
//result is: 13230000014.560297
printf("The disk health in loop is: %i\n", (int) floor(disk_ptr->health));
//result is: -2147483648
printf("The disk health in loop is: %d\n", (int) floor(disk_ptr->health));
//result is: -2147483648
The code above is what I am using. I want the second result to output: 13230000014, but instead it is giving me a strange negative number.
Upvotes: 0
Views: 219
Reputation: 702
You said that you want it to print 13230000014
, but this value is greater than the maximum value than an int can hold, which is actually 2^31 - 1
(on most systems). You would need to stop using the %i
specifier and switch to a bigger specifier, like %lld
, and cast to a long long
instead.
Like this:
printf("The disk health in loop is: %lld\n", (long long) floor(disk_ptr->health));
Note that you have to change both the casting as well as the format specifier, or printf
will still treat the argument as an int.
If you want to be more explicit about using a 64 bit integer, you can consider including stdint.h
, and making a cast to int64_t
instead of a long long
.
EDIT: Note that the floor call is redundant in your case, as casting to long long
will automatically truncate the decimal. I left it in the above example to better match your code, but just know that it isn't necessary.
Upvotes: 7
Reputation: 15171
13230000014
is larger than a 32-bit integer, so you can't store it in an int
if an int
is 32 bits. If you have a 64-bit computer, you can try casting to a long
instead of an int
. Note that long
is not guaranteed to be 64 bits.
Edit: According to the comments, the types int64_t
and long long
are guaranteed to be 64 bits, so you can use those.
Upvotes: 7