Problems with the double variable type
Author |
Message |
ihsh
|
Posted: Sat Sep 04, 2010 10:01 pm Post subject: Problems with the double variable type |
|
|
I had been trying to do some write some functions with 5 digit nums (which you have to do double, right), but it never worked, and the values were really strange. So I disabled my calculation parts so that the program basically received the input and output the same value.
And here was the problem: The values are just wrong! I had the same problem with functions/ doubles before, but I managed to fix it using plain float variables. But this time it just seems impossible!
code: |
#include <stdio.h>
double digitSum (double b);
void main ()
{
double a;
printf ("\n\nEnter 5-digit number: ");
scanf ("%f", &a);
printf ("%f", a); /*Always returns zero*/
printf ("\nDigit sum: %f", digitSum (a));
}
double digitSum (double b)
{
printf ("\n%f", b);
return (b);
}
|
Again, thanks for your help. |
|
|
|
|
|
Sponsor Sponsor
|
|
|
DtY
|
Posted: Sat Sep 04, 2010 10:47 pm Post subject: RE:Problems with the double variable type |
|
|
Only use floating point numbers (including double) if you actually need to store non integers (or accuracy is very unimportant).
The thing about floating point arithmetic is that numbers can either be accurate or big. They can be very big, but they lose accuracy, if they're really small (especially less than one), they have a lot of accuracy. In more technical terms, the numbers are limited in number of significant figures in base two (see wikipedia (https://secure.wikimedia.org/wikipedia/en/wiki/Significant_figures ) if you are not familiar with significant figures).
In C, a long int is guaranteed to be at least 32 bits long, which is big enough to store any five digit number (signed longs will be good enough). Most modern compilers will make standard ints 32 bits long, but they're only guaranteed to be 16 bits long.
So basically, use an integer. |
|
|
|
|
|
ihsh
|
Posted: Mon Sep 06, 2010 8:43 pm Post subject: RE:Problems with the double variable type |
|
|
Thank you. My program successfully ran. |
|
|
|
|
|
Xupicor
|
Posted: Tue Feb 22, 2011 8:21 pm Post subject: RE:Problems with the double variable type |
|
|
You need to use %lf to be able to use scanf() with double (%f - float, %lf - double, %Lf - long double).
You may not know this, because printf will work using %f regardless of the value being float or double, that's because the float value is being implicitly converted to double on function call anyway. No, not on every function call - only on a variadic function call, and printf is a variadic function.
scanf however needs to know exactly to what type the pointer is going to be used. |
|
|
|
|
|
|
|