Home > Back-end >  C integer floating-point conversion small problem
C integer floating-point conversion small problem

Time:02-19

In the learning process encountered a problem, first defines a a floating point number a=1.5, I want to send him to expand ten times, ten times before narrowing
The following figure, a return not the original value, for the first time


then I thought of the following method, don't know right



But the problem is though and had a values are equal in size, but not a floating-point number, and not the same as the original, to 1.500000000, the how can into the same 1.5 ? (this a is in the single chip microcomputer)

CodePudding user response:

I'm afraid this and printf % f format, if the default decimal six, I think is 1.5

CodePudding user response:

Somebody else's system output 5 0, you knocked 8 0, the text is visible you can think more than a few less several 0 at the end of it doesn't matter,

CodePudding user response:

So you have to express clearly, you care about what is the value or format?

CodePudding user response:

 # include & lt; stdio.h> 
Int main ()
{
Float a=1.5;
Printf (" first a=% f \ n ", a);//the original
Int a_10;
A_10=(int) (a * 10);
Printf (" a_10=% d \ n ", a_10);
A=a_10/10.0;
Second printf (" a=% f \ n ", a);//now

return 0;
}

//first a=1.500000
//a_10=15
//the second a=1.500000
//please press any key to continue...

CodePudding user response:

Here involves when floating-point and integer transform,
Equation a=a_10/10; A floating point, a_10 for integer
In order to facilitate, formula into a=a_10/10 + 3;

Is it is a problem to a_10 directly into a floating-point then in addition to the operation of 10 + 3, (integer division does not retain remainder, this is the difference between with floating-point arithmetic, this will affect the final result)
Or a_10/10 after the operation to a floating point and then add 3,
Or a_10/10 + 3 after all the operation in turn,

The compiler is actually, according to the number 10 or 10.0 for 3 or 3.0 to distinguish
Integer to integer arithmetic a_10/10, a_10/10 + 3 or carried out in accordance with the integer arithmetic way
Integer and floating point arithmetic a_10/10.0 will put a_10 into a floating-point operation with 10.0,
  • Related