How can I conver string to double value in c? - c

I want to get the equivalent double number of any word.
I use atof, but it give me zero output.
How can I solve it
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("%f\n", *(double*)"hello");
}

That's because you did not read the documentation of atof(), or strtod()
https://www.tutorialspoint.com/c_standard_library/c_function_strtod.htm
http://www.cplusplus.com/reference/cstdlib/strtod/

Doubles are floating point numbers, essentially non-integer numbers.
"hello" is not a valid string representation of a double. Try a number instead, for example
printf("%f\n", atof("3.141"));

Related

Why does casting to int not floor all doubles in C

Given the C code:
#include <math.h>
#include <stdio.h>
int main(){
int i;
double f=log(2.0)/log(pow(2.0,1.0/2.0));
printf("double=%f\n",f);
printf("int=%d\n",(int) f);
}
I get the output:
double=2.000000
int=1
f is apparently at least 2.0. Why is the cast value not 2?
Because the value of the double was less than 2
double=1.99999999999999978
int=1
Try it but this time add some precision
#include <math.h>
#include <stdio.h>
int main(){
int i;
double f=log(2.0)/log(pow(2.0,1.0/2.0));
printf("double=%0.17f\n",f);
printf("int=%d\n",(int) f);
}
Confusing as hell the first time you experience it. Now, if you try this
#include <math.h>
#include <stdio.h>
int main(){
int i;
double f=log(2.0)/log(pow(2.0,1.0/2.0));
printf("double=%0.17f\n",f);
printf("int=%d\n",(int) f);
printf("int=%d\n", (int)round(f));
}
It will correctly round the value. If you look in the man page (on a mac at least) you'll see the following comment...
round, lround, llround -- round to integral value, regardless of rounding direction
What do they mean by direction, it's all specified in IEEE 754. If you check the different ways to round to an integer... floor is mentioned as rounding towards -ve infinity which is in this case was towards 1 :)
Floating point types are unable to represent some numbers exactly. Even though mathematically, the calculation should be exactly 2, with IEEE754 floating points, the result turns out to be slightly less than 2. For more information see this question.
If you increase the precision of your output by specifying %.20f instead of just %f, you will see that the number is not exactly 2, and that when printing with less accuracy, the result is simply rounded.
When converting to an int however, the full accuracy of the floating point type is used, and since it comes to just under 2, the result when converting to an integer is 1.
Integer does not take a rounded up value but makes a truncation. So, if f is equal to 1.999999999999[..]9, the int value will be 1.
Also, as the double wants to be the more accurate possible, he will take a rounded up value considering the number of characters he can show, which is 2.000000.

Power function returns 1 less result

Whenever I input a number in this program the program return a value which is 1 less than the actual result ... What is the problem here??
#include<stdio.h>
#include<math.h>
int main(void)
{
int a,b,c,n;
scanf("%d",&n);
c=pow((5),(n));
printf("%d",c);
}
pow() returns a double, the implicit conversion from double to int is "rounding towards zero".
So it depends on the behavior of the pow() function.
If it's perfect then no problem, the conversion is exact.
If not:
1) the result is slightly larger, then the conversion will round it down to the expected value.
2) if the result is slightly smaller, then the conversion will round down which is what you see.
solution:
Change the conversion to "round to nearest integer" by using rounding functions
c=lround(pow((5),(n)));
In this case, as long as pow() has an error of less than +-0.5 you will get the expected result.
pow() takes double arguments and returns a double.
If you store the return value into an int and print that, you may not get the desired result.
If you need accurate results for big numbers, you should use a arbitrary precision math library like GMP. It's easy:
#include <stdio.h>
#include <math.h>
#include <gmp.h>
int main(void) {
int n;
mpz_t c;
scanf("%d",&n);
mpz_ui_pow_ui(c, 5, n);
gmp_printf("%Zd\n", c);
return 0;
}
You can use the %f format specifier while commanding printf func.You should see your result accurately. In %d format specifier the value tends to the final answer eg. 5^2=24.9999999999 and hence the answer shown is 24.

declaring a variable with only 2 decimal points in C

I am trying to declare a variable eLon with only 1 decimal place so that if I have the code:
elon=359.8
printf("eLon = %f\n",eLon);
and the output will be
eLon = 359.8
However the output I get is:
eLon = 359.7999999.
How I know that I could modify the printf so that it would be:
printf(eLon is %0.1f\n",eLon);
to get the desired result. This is NOT what I want to do. I just want the variable itself to only have one decimal place so that it equals 359.8 not 359.7999999, since this is critical for any computations I make. Do you know how I should modify my code to get the desired result. I tried doing what was suggested in other inquiries but it did not work for example the code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int endLonn;
float endLon,eLon;
endLon=359.8;
endLonn=359.8*10;
printf("%d is endLonn\n",endLonn);
eLon= endLonn / 10;
printf("elon is %f\n",eLon);
}
gives me the output:
elon is 359.00000000
Again this is also not what I am looking for. I want elon is 359.8. If you could help me tweak my code to get the desired result that would be great. Thank you for your time.
Instead of trying to cheat double or float and printf, you can use fixed point arithmetic. In the particular case of your example you will express variable in 0.1s of it's original value:
int in_10s;
in_10s=3598;
printf("My fixed point variable "
"represents %d.%01d value\n",
in_10s/10, abs(in_10s % 10));
In general case of n decimal places, the format to printf should be %d.%0nd, where n=log_10(scaling_factor^-1), and scaling factor is interpreted like here.
What you want is not a floating point number but a fixed point decimal, which is for example available in c# as decimal. c doesn't give you that. There are two "typical" approaches to roll your own:
Use a plain int and just have the decimal point at some position by convention. e.g. your value would be int elon=3598.
Use a struct with two ints, one for the whole number part and one for the amount of tenths (or hundredths, thousandths, ...)
In both cases, you will need to implement your own logic for output. The simple approach using a plain int at least lets you use basic arithmetics as usual.
You actually can't declare a variable to hold only one decimal figure. The only native types able to represent non-integer values are floating point types, on which any arithmetic operation which yield a value of the same nature. Floating point types cannot be limited to a fixed number of decimal figures.
In order to achieve what you are asking for, you have to either implement such behavior or use an existing implementation of what is called fixed-point airthmetic.
A pretty complete introduction can be found in Wikipedia's Fixed-Point arithmetic entry. At the end you will find a couple of libraries implementing it.
I just want the variable itself to only have one decimal place so that it equals 359.8 not 359.7999999,
You should use double:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(void){
int endLonn;
double endLon,eLon;
endLon=359.8;
endLonn=359.8*10;
printf("%d is endLonn\n",endLonn);
eLon = endLonn / 10;
printf("elon is %.1lf\n%.1lf",eLon,endLon);
return 0;
}
Output:
3598 is endLonn
elon is 359.0
359.8

Why the same value of float and a string that is converted into float using function atof are not equal?

I have written a program in C and when I compare the same values of a float and a string that is converted into float using function atof results in NOT EQUAL .
#include<stdio.h>
main(){
char str[10] = "54.23" ;
float val = 54.23 ;
if( atof(str) == val )
printf("\nconverted correctly");
else
printf("\nThen What is the use of atof\n ");
}
This Program is showing output : "Then What is the use of atof"
Please tell me why this anonymous behavior is shown by this program ?
Never test floats/doubles for equality with ==
Here's a version of your code which actually displays the values in question:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10] = "54.23";
float val = 54.23;
printf("atof(str) = %.15f\n", atof(str));
printf(" val = %.15f\n", val);
return 0;
}
When you run it you see this:
$ gcc -Wall atof.c
$ ./a.out
atof(str) = 54.229999999999997
val = 54.229999542236328
$
The values are close, within the expected accuracy of a single precision float, but they are not identical. Also, as others have noted, atof returns a double, so you are comparing the value of a float promoted to a double with a full precision double as returned by atof.
As always with this type of question, read this before proceding any further with floating point arithmetic in your code. The "take home message" is that you should never compare floats or doubles with == - always compare the absolute difference with an appropriate tolerance value.
Because val is an int; when you assign it 54.23 it'll be truncated to 54. And 54 != 54.23.
Even if it was a float, you couldn't expect them to be equal. Here's why.
double atof(char *str);\\it return double not a float
This comparison is between a float and a double.As you compare between two different types you may get some unexpected output.because every data type having different memory representation as well as different access mechanism.
float represent in memory in different form as compare to double .
you can learn more about this in wikipedia also
http://en.wikipedia.org/wiki/Floating_point#Internal_representation
Again you should include the header file
#include <stdlib.h> \\prototype of atof() present in this header.
if you not provide the proper prototype before use of the function then
return type of function by default int .So I think the return result is definitely different as you expected.
You almost never want to check equality with floating point numbers, because teensy differences will be read as unequal. There are other problems, too. For example, even if you use double precision, for instance, the decimal number "0.1" is represented as "0.10000000000000001".
In this case, your "val" variable is a double precision literal, which is cast to a float. The result probably won't be accurate perfectly. Secondly, your string literal needs to convert from base ten to a base 2 double. So, to compare the atof value to your literal, atof converts a base ten string to a base two double, while "val" was converted from a base ten literal to a base two double to a base two float, and then upcast back to a base two double to do the comparison.
Point of fact, I'm not going to pin down exactly where that lost precision went. Do as Paul's code might suggest and compare the values to within a tolerance.

Convert Int to Hexdecimal without using 'printf' (C Programming)

Is it possible to Convert Int to Hexdecimal without using 'printf'?
Best if the all the value are placed in the variable itself and some sample code with explanation.
The decimal and hexadecimal systems are just ways of expressing the value of the int. In a way "it is already a hexadecimal".
I think you can use itoa in stdlib.h :
char * itoa ( int value, char * str, int base ); or sprintf(str,"%x",value);
The documentation : itoa documentation
Of course it is possible. Just think about how printf itself was originally implemented...
I won't give you a full solution, only hints, based on which you can experiment with the implementation in code:
An 8-bit number can be expressed as 2 hex digits, which contain the higher and lower 4 bits, respectively. To get these bits, you can use the bit-shift (>>) and mask (&) operators.
Once you have a 4-bit value, you can easily map it to the correct hex digit using a sequence of ifs, or (as a more elegant solution) by indexing into a character array.
Hexdecival vs Decimal vs Binary..etc.. are only different bases that represent the same number. printf doesn't convert your number, it generates an hexdecimal string representation of your number. If you want to implement your own study how to make a conversion between decimal and hexdecimal bases.
Yes, it is definitely possible to convert an integer to a hexadecimal string without using the "printf" family of formatting functions.
You can write such a function by converting the number from base-10 (as we think about it) to base-16 (hexadecimal) and printing the digits in that representation (0-9A-F). This will require you to think a lot about the bases we use to represent numbers.
If you are referring to displaying an int as a hexadecimal number in C, than you will have to write a function that does the same thing as printf.
If you are referring to casting or internal representation, it can't be done because hexadecimal is not a data type.
An int is stored in your computer as a binary number. In fact, since hex can be interpreted as a shorthand for writing binary, you might even say that when you print out a decimal number using printf, it has to be converted from hex to decimal.
it's an example for convert a char array to hex string format
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
unsigned char d=255;
char hex_array[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char *array_to_hex_string(uint8_t data[],int size);
char test_data[3] = {'0',188,255};
int main()
{
printf("%s",array_to_hex_string(test_data,3));
return 0;
}
char *array_to_hex_string(uint8_t data[],int size){
int i,j;
char *hex_string = (char *)malloc((2*size) * sizeof(data[0]));
for(i=0;i<size;i++){
hex_string[j] = hex_array[(data[i]>>4)];
hex_string[j+1] = hex_array[(data[i] & 15)];
j +=2;
}
return (char *)hex_string;
}
cout << hex << intvar << endl;
But if you want an answer that gives you an A for your homework, you're not going to get lucky :)

Resources