how to keep decimals in c - c

I am writing simple code for homework.
I get one number from user, which is 3.4, when I define it with
scanf("%d",&a)
it takes only 3 and do it that way. I defined a as
int a;
What should I do?

I think you are very new to c programming. This is a very simple job. This can be done as:-
float a;
// to input a data in the variable a
scanf("%f",&a);
//to display the stored data
printf("%f\n",a);
//or
printf("%.nf\n",a);//specify value of n
//maximum value of n is 6 also is its default value
//for e.g. printf("%.2f",a); will display decimal number upto two digits after the decimal place
//you can know more about displaying data as
%d: decimal value (int)
%c: character (char)
%s: string (const char *)
%u: unsigned decimal value (unsigned int)
%ld: long int (long)
%f: float value (float or double)
%x: decimal value in Hexadecimal format
%o: decimal value in octal format
For avialabe list of formatting specifications go here

Use float
float a;
scanf("%f", &a);

%d is for int. 3.4 is not an int type, you can use float.
float x;
scanf("%f", &x);
For detailed information about data types, you can check here: http://en.wikipedia.org/wiki/C_data_types
And also here: http://www.techonthenet.com/c_language/variables/index.php

You should define a as
float a;
and replace %d with %f in scanf
scanf("%f", &a);
What should I do?
Read Basics of Formatted Input/Output in C.

Its very simple for int variable we use %d format specifier and if we want float we use %f format specifier. Because according to IEEE int and float bit map format are different.

You are declaring int a which can take only integer value so what you have to do is make it float which is used for numbers having decimal point
float a;
scanf(%f,&a);

Related

How can I fix my floats being rounded down to doubles?

I know that by default in C when you declare a float it gets automatically saved as a double and that if you want it to be saved as a float you have to declare it like this
float x = 0.11f
but what if my x value comes from a scanf? How can I do so that when I print it it doesn't get rounded down or up?
Here's my code btw, thanks for the help.
#include <stdio.h>
int main() {
float number = 0;
float comparison;
do{
printf("\nEnter a number: ");
scanf("%f", &comparison);
if(comparison > number) {
number = comparison;
}
}while(comparison > 0);
printf("The largest number enteres was: %f\n\n", number);
}
what if my x value comes from a scanf? How can I do so that when I print it it doesn't get rounded down or up?
scanf with an %f directive will read the input and convert it to a float (not a double). If the matched text does not correspond to a number exactly representable as a float then there will be rounding at this stage. There is no alternative.
When you pass an argument of type float to printf() for printing, it will be promoted to type double. This is required by the signature of that function. But type double can exactly represent all values of type float, so this promotion does not involve any rounding. printf's handling of the %f directives is aligned with this automatic promotion: the corresponding (promoted) argument is expected to be of type double.
There are multiple avenues to reproducing the input exactly, depending on what constraints you are willing to put on that input. The most general is to read, store, and print the data as a string, though even this has its complications.
If you are willing to place a limit on the maximum decimal range and precision for which verbatim reproduction is supported, then you may be able to get output rounded to the same representation as the input by specifying a precision in your printf field directives:
float f;
scanf("%f", &f);
printf("%f %.2f %5.2f\n", f, f, f);
If you want to use a built-in floating-point format and also avoid trailing zeroes being appended then either an explicit precision like that or a %g directive is probably needed:
printf("%f %g\n", f, f);
Other alternatives are more involved, such as creating a fixed-point or arbitrary-precision decimal data type, along with appropriate functions for reading and writing it. I presume that goes beyond what you're presently interested in doing.
Note: "double" is short for "double precision", as opposed to notionally single-precision "float". The former is the larger type in terms of storage and representational capability. In real-world implementations, there is never any "rounding down" from float to double.

C double value not stored using scanf

So what is happening is I ask the user for input, then store that into a variable using scanf.
But when I try to retrieve the value, it just a 0.000000. I'm sure I'm just making a stupid noob mistake, but any help you can provide is appreciated.
printf("Enter the radius of your circle/sphere: ");
scanf("%f", &radius);
printf("\n%f", radius);
Ex:
Enter the radius of your circle/sphere: 10
0.0000000
Thanks for your time!
As answered by #Chris McGrath, you must use the %lf format specifier for doubles. However, this doesn't explain why the %f format works just fine for printf.
%lf stands for long float, i.e. double. When values of type float are passed to variadic functions (those accepting a variable number of arguments, such as printf and scanf), they are implicitly promoted to double:
float val;
printf("%f", val); /* printf receives val cast to double, the same
as printf("%f", (double) val) */
printf("%lf", val); /* printf also receives val cast to double, the
same as printf("%lf", (double) val) */
Since both printf("%lf", ...) and printf("%f", ...) end up receiving a double, the two are completely equivalent.
On the other hand, all arguments to scanf are pointers. scanf("%f", ...) expects to receive a float *, and scanf("%lf", ...) a double *:
float floatval;
double dblval;
scanf("%f", &floatval); /* stores a float value to address received */
scanf("%lf", &dblval); /* stores a double value to address received */
The two pointers point to different types, so one cannot be promoted to the other. If they received the same treatment by scanf, it would end up storing the same value into addresses allocated for types of different size, which cannot work.
This is why scanf strictly requires the use of the %lf specifier when used with double values.
As AntonH said, if radius is declared as a double, you must use the %lf format specifier:
scanf("%lf", &radius);

Is it possible to print a float with user-defined precision after decimal point in C?

I want to print out a float with a user-defined precision after decimal point in C, like say,
int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
Then print the number no with dec decimal places.
You may format the printing of a floating point number, but not its actual size.
You may read this on formatting floating point number.
To save your time, you may use the %f format specifier, as
printf("%.PRECISIONf", fvar);
where PRECISION is the number of digits you want after decimal, for e.g.
int
print_float(float fvar, unsigned int precision) {
char fs[32];
sprintf(fs,"%%.%df", precision);
return printf(fs, fvar);
}
On calling the routine:
print_float(2.0f, 2);
you will get 2.00 as the output.
Hope this solves your issue.
Do
int dec;
float no;
printf("\nEnter no of decimal places and the number ");
scanf("%d%f",&dec,&no);
printf("%.*f",dec,no);

Printf variable number of decimals in float

I found interesting format for printing nonterminated fixed length strings like this:
char newstr[40] = {0};
sprintf(newstr,"%.*s", sizeof(mystr), mystr);
So I think maybe is there a way under printf command for printing a float number...
"%8.2f"
to have ability to choose number of decimals with integer number.
Something like this:
sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)
You can also use ".*" with floating points, see also http://www.cplusplus.com/reference/cstdio/printf/ (refers to C++, but the format specifiers are similar)
.number: For a, A, e, E, f and F specifiers: this is the number of digits to be
printed after the decimal point (by default, this is 6).
...
.*: The precision is not specified in the format string, but as an
additional integer value argument preceding the argument that has to
be formatted.
For example:
float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
Output:
42.35
You can use the asterisk for that too, both for the field width and the precision:
printf("%*.*f\n", myFieldWidth, myPrecision, myFloatValue);
See e.g. this reference.
If, for some reason, your actual C library doesn't support variable precision and width for float formatting, it's not too hard to build the format string your own:
char fmt[6 + 3*(sizeof width + sizeof precision)]; /* sufficient space */
sprintf(fmt, "%%%d.%df\n", width, precision);
printf(fmt, value);
Of course this comes at a cost, but - depending on your situation - this can be maybe centralized.

Convert int to double

I ran this simple program, but when I convert from int to double, the result is zero. The sqrt of the zeros then displays negative values. This is an example from an online tutorial so I'm not sure why this is happening. I tried in Windows and Unix.
/* Hello World program */
#include<stdio.h>
#include<math.h>
main()
{ int i;
printf("\t Number \t\t Square Root of Number\n\n");
for (i=0; i<=360; ++i)
printf("\t %d \t\t\t %d \n",i, sqrt((double) i));
}
Maybe this?
int number;
double dblNumber = (double)number;
The problem is incorrect use of printf format - use %g/%f instead of %d
BTW - if you are wondering what your code did here is some abridged explanation that may help you in understanding:
printf routine has treated your floating point result of sqrt as integer. Signed, unsigned integers have their underlying bit representations (put simply - it's the way how they are 'encoded' in memory, registers etc). By specifying format to printf you tell it how it should decipher that bit pattern in specific memory area/register (depends on calling conventions etc). For example:
unsigned int myInt = 0xFFFFFFFF;
printf( "as signed=[%i] as unsigned=[%u]\n", myInt, myInt );
gives: "as signed=[-1] as unsigned=[4294967295]"
One bit pattern used but treated as signed first and unsigned later. Same applies to your code. You've told printf to treat bit pattern that was used to 'encode' floating point result of sqrt as integer. See this:
float myFloat = 8.0;
printf( "%08X\n", *((unsigned int*)&myFloat) );
prints: "41000000"
According to single precision floating point encoding format.
8.0 is simply (-1)^0*(1+fraction=0)*2^(exp=130-127)=2*3=8.0 but printed as int looks like just 41000000 (hex of course).
sqrt() return a value of type double. You cannot print such a value with the conversion specifier "%d".
Try one of these two alternatives
printf("\t %d \t\t\t %f \n",i, sqrt(i)); /* use "%f" */
printf("\t %d \t\t\t %d \n",i, (int)sqrt(i)); /* cast to int */
The i argument to sqrt() is converted to double implicitly, as long as there is a prototype in scope. Since you included the proper header, there is no need for an explicit conversion.

Resources