anyone care to help me here ??
Printable View
anyone care to help me here ??
Yes of course, i assume you have a decimal number as a string, like "123.4567" and you need a variable of type double to hold the result.
The function you need is atof, and is in the <stdlib.h>.
For reasons unknown to me i would prefer to use strtod.
is there any way to convert a string to an int in C? how about if I have a decimal number as a double?? how would I convert that to a floating point??
Be more specific, show some of what you need to convert.
Check this out.
okay here's an example.. say that I have a decimal number of 10 and I want to extract it to +1.0100000000000000000000e+3, something like that
You mean an assignment?
or a conversion from text?Code:int a = 10;
double d = (double)a;
Code:char s[] = "10";
double d = atof(s);
yes I mean an assignment, not from a text
+1.0100000000000000000000e+3 is 1010
so how you can "extract" 10 to this value?
to assign 10 you use
double a = 10;
to print it in the scientific notation - use %g format of printf - read about formats of printf and what formating they provide
Or,The original number posted has 22 decimal places, which is about 5 more than you can expect to get out of a "double". Some compilers and processors have larger floating point numbers "long double", implememented with for example the "80-bit Extended precision" of x86, that can give more digits - in the x86 case, you can expect about 20 digits precision with this.Code:double a = 10.0;
If you need more precise values, you need to use a special math library, such as GMP.
--
Mats
and how would I convert the decimal to binary?? is there a specific command in C that would allow me to do this?? or do I have to do this manually?
You have to do it manually, but it's not too hard. The only problem I can think of is deciding how to store the binary value. A string makes the most sense.
Code:#include <stdio.h>
// Return a value with the bit specified
// by i set and all other bits unset
#define bitmask(i) (1U << i)
int main()
{
// The number of bits in an int
const int intSize = 31;
// The decimal number to convert
int value;
int i;
printf("Please enter a decimal number to be converted: ");
scanf("%d", &value);
// Print the bits of the decimal value
for (i = intSize; i >= 0; --i)
{
// Assume bitmask(i) is unset
char bit = '0';
// Pick the character to print
if (value & bitmask(i))
{
bit = '1';
}
putchar(bit);
}
putchar('\n');
return 0;
}
Itoa can convert a number into base 2, if you will, but it's not a standard function.
I don't know of any other function to do it, though.
the code you supplied generates an error.. it's on the define part.. I know know what's wrong with that
The code compiles fine.
What compiler do you use?
I used this to compile gcc -ansi -Wall binary.c -o binary
and it says error: expected identifier or "(" before '/' token