I want to put the number in the left hand side of the float point in a new variable
from a float number ex:
int var1;
float var2;
float x=12.505; // i want the number 12 to put it in "var1" and 0.505 in "var2"
It's very simple if you know that when you convert a floating point value to an integer, it simply truncates the floating point value. So you could simply do
var1 = x; // Assign 12 to var1
var2 = x - var1; // Assigns 12.505 - 12 to var2
var1 = x; // var1 is 12
var2 = x - var1; // var2 is 0.505
Run live.
Note that,
If the conversion is from a floating-point type to an integer type, the value is truncated (the decimal part is removed). If the result lies outside the range of representable values by the type, the conversion causes undefined behavior.
Read more about Type conversions.
You can cast the float to int, using one of the options below:
var1 = (int)x;
var1 = static_cast<int>(x);
var1 = int(x);
All these options are identical. Also, you can use implicit conversion, but it can cause compile warnings or errors depending on your compiler settings:
var1 = x;
After this conversion you will need to calculate the fractional part:
var2 = x - var1;
Please note that direct conversion to int truncates the fractional part, I mean,
(int)(12.505) == 12
(int)(12.499) == 12
(int)(-12.55) == -12
(int)(-12.49) == -12
If you need some other ways of rounding the number, use ceil(), floor() or round(). These functions are located in header file in std namespace.
There are various ways.
For one way, look up the function modf() in the standard header <math.h>
Just use auto truncate functionality.
float f = 12.93;
int b = f; // 12
float p = f - b // 0.93
Related
I was writing this code:
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
The result is 0. Why is this, and how do I solve this problem?
The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.
Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)
Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....
1/3 uses integer division as both sides are integers.
You need at least one of them to be float or double.
If you are entering the values in the source code like your question, you can do 1.0/3 ; the 1.0 is a double.
If you get the values from elsewhere you can use (double) to turn the int into a double.
int x = ...;
int y = ...;
double value = ((double) x) / y;
Explicitly cast it as a double
double g = 1.0/3.0
This happens because Java uses the integer division operation for 1 and 3 since you entered them as integer constants.
Because you are doing integer division.
As #Noldorin says, if both operators are integers, then integer division is used.
The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.
If any of the operators is a double / float, then floating point arithmetic will take place. But you'll have the same problem if you do that:
int n = 1.0 / 3.0;
The easiest solution is to just do this
double g = (double) 1 / 3;
What this does, since you didn't enter 1.0 / 3.0, is let you manually convert it to data type double since Java assumed it was Integer division, and it would do it even if it meant narrowing the conversion. This is what is called a cast operator.
Here we cast only one operand, and this is enough to avoid integer division (rounding towards zero)
The result is 0. Why is this, and how do I solve this problem?
TL;DR
You can solve it by doing:
double g = 1.0/3.0;
or
double g = 1.0/3;
or
double g = 1/3.0;
or
double g = (double) 1 / 3;
The last of these options is required when you are using variables e.g. int a = 1, b = 3; double g = (double) a / b;.
A more completed answer
double g = 1 / 3;
This result in 0 because
first the dividend < divisor;
both variables are of type int therefore resulting in int (5.6.2. JLS) which naturally cannot represent the a floating point value such as 0.333333...
"Integer division rounds toward 0." 15.17.2 JLS
Why double g = 1.0/3.0; and double g = ((double) 1) / 3; work?
From Chapter 5. Conversions and Promotions one can read:
One conversion context is the operand of a numeric operator such as +
or *. The conversion process for such operands is called numeric
promotion. Promotion is special in that, in the case of binary
operators, the conversion chosen for one operand may depend in part on
the type of the other operand expression.
and 5.6.2. Binary Numeric Promotion
When an operator applies binary numeric promotion to a pair of
operands, each of which must denote a value that is convertible to a
numeric type, the following rules apply, in order:
If any operand is of a reference type, it is subjected to unboxing
conversion (§5.1.8).
Widening primitive conversion (§5.1.2) is applied to convert either or
both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted
to float.
Otherwise, if either operand is of type long, the other is converted
to long.
Otherwise, both operands are converted to type int.
you should use
double g=1.0/3;
or
double g=1/3.0;
Integer division returns integer.
Make the 1 a float and float division will be used
public static void main(String d[]){
double g=1f/3;
System.out.printf("%.2f",g);
}
The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
And an example is always the best way to translate the JLS ;)
int + long -> long
int(1) + long(2) + int(3) -> long(1+2) + long(3)
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
short + int -> int + int -> int
A small example using Eclipse to show that even an addition of two shorts will not be that easy :
short s = 1;
s = s + s; <- Compiling error
//possible loss of precision
// required: short
// found: int
This will required a casting with a possible loss of precision.
The same is true for the floating point operators
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
So the promotion is done on the float into double.
And the mix of both integer and floating value result in floating values as said
If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.
This is true for binary operators but not for "Assignment Operators" like +=
A simple working example is enough to prove this
int i = 1;
i += 1.5f;
The reason is that there is an implicit cast done here, this will be execute like
i = (int) i + 1.5f
i = (int) 2.5f
i = 2
1 and 3 are integer contants and so Java does an integer division which's result is 0. If you want to write double constants you have to write 1.0 and 3.0.
I did this.
double g = 1.0/3.0;
System.out.printf("%gf", g);
Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.
Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.
To get the result you are looking for, explicitly tell java that the numbers are doubles like so:
double g = 1.0/3.0;
(1/3) means Integer division, thats why you can not get decimal value from this division. To solve this problem use:
public static void main(String[] args) {
double g = 1.0 / 3;
System.out.printf("%.2f", g);
}
public static void main(String[] args) {
double g = 1 / 3;
System.out.printf("%.2f", g);
}
Since both 1 and 3 are ints the result not rounded but it's truncated. So you ignore fractions and take only wholes.
To avoid this have at least one of your numbers 1 or 3 as a decimal form 1.0 and/or 3.0.
My code was:
System.out.println("enter weight: ");
int weight = myObj.nextInt();
System.out.println("enter height: ");
int height = myObj.nextInt();
double BMI = weight / (height *height)
System.out.println("BMI is: " + BMI);
If user enters weight(Numerator) = 5, and height (Denominator) = 7,
BMI is 0 where Denominator > Numerator & it returns interger (5/7 = 0.71 ) so result is 0 ( without decimal values )
Solution :
Option 1:
doubleouble BMI = (double) weight / ((double)height * (double)height);
Option 2:
double BMI = (double) weight / (height * height);
I noticed that this is somehow not mentioned in the many replies, but you can also do 1.0 * 1 / 3 to get floating point division. This is more useful when you have variables that you can't just add .0 after it, e.g.
import java.io.*;
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 15;
System.out.println(1.0 * x / y);
}
}
Do "double g=1.0/3.0;" instead.
Many others have failed to point out the real issue:
An operation on only integers casts the result of the operation to an integer.
This necessarily means that floating point results, that could be displayed as an integer, will be truncated (lop off the decimal part).
What is casting (typecasting / type conversion) you ask?
It varies on the implementation of the language, but Wikipedia has a fairly comprehensive view, and it does talk about coercion as well, which is a pivotal piece of information in answering your question.
http://en.wikipedia.org/wiki/Type_conversion
Try this out:
public static void main(String[] args) {
double a = 1.0;
double b = 3.0;
double g = a / b;
System.out.printf(""+ g);
}
This question already has answers here:
C++ program converts fahrenheit to celsius
(8 answers)
Closed 7 years ago.
First of all, I want to say sorry because I think the doubt is so trivial... but I'm new programming in C++.
I have the following code:
int a = 234;
int b = 16;
float c = b/a;
I want to print the result from float c with 2 decimals (the result should be 0.06) but I don't get the expected result.
Can anyone can help me? I tried using CvRound() and setPrecision() but nothing works like I expect or, in my case, I don't know how to do them working.
The problem is actually blindingly simple. And has NOTHING whatsoever do do with settings such as precision.
a and b are of type int, so b/a is also computed to be of type int. Which involves rounding toward zero. For your values, the result will be zero. That value is then converted to be float. An int with value zero, when converted to float, gives a result of 0.0. No matter what precision you use to output that, it will still output a zero value.
To change that behaviour convert one of the values to float BEFORE doing the division.
float c = b/(float)a;
or
float c = (float)b/a;
The compiler, when it sees a float and and an int both participating in a division, converts the int to float first, then does a division of floats.
int a = 234;
int b = 16;
float c = b/(float)a;
float rounded_down = floorf(c * 100) / 100; /* floor value upto two decimal places */
float nearest = roundf(c * 100) / 100; /* round value upto two decimal places */
float rounded_up = ceilf(c * 100) / 100; /* ceiling value upto two decimal places */
If you just want to print the result, you can use a printf() formatting string to round:
printf("c = %.2f\n", number, pointer);
Otherwise, if you need c to calculate another value, you shouldn't round the original value, only the one to print.
try this:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int a = 234;
int b = 16;
float c = float(b)/a;
cout<<fixed<<setprecision(2)<<c;
return 0;
}
Previously when c = b/a since a and b are integers so by integer division we were getting answer as 0 as per your program.
But if we typecast one of the variable(a or b) to float we will obtain decimal answer.
Number of digits after decimal may or may not be 2. To ensure this we can use fixed and setprecision. fixed will ensure that number of digits after decimal will be fixed. setprecision will set how many digits to be there after decimal.
I am currently programming an arduino and am using C++ objects to do so. I've run into a weird issue when I try to multiply the values that are being pointed at. Referring to the code below, when I run the program, var3 and var4 end up having two different values. Why is this? They are essentially multiplying the same values (or so I believe). Any help?
long var1 = info->accelXYZ[0];
long var2 = info->taughtAccelXYZ[0];
long var3 = var1*var2;
long var4 = info->accelXYZ[0]*info->taughtAccelXYZ[0];
It's possible you're overflowing in one of the situations.
The multiplication of var1 and var2 (both long) gives a long which is then loaded into var3.
If both info->accelXYZ[0] and info->taughtAccelXYZ[0] are int (for example), the result of the multiplication will be int which is then loaded into a long.
The intermediate int form may be overflowing, something you can see in the following snippet:
#include <stdio.h>
#include <limits.h>
int main(void) {
printf("int has %d bytes\n",sizeof(int));
printf("long has %d bytes\n",sizeof(long));
int a = INT_MAX;
int b = 2;
long var1 = a;
long var2 = b;
long var3 = a * b;
long var4 = var1 * var2;
printf ("var3=%ld\n", var3);
printf ("var4=%ld\n", var4);
return 0;
}
which outputs:
int has 4 bytes
long has 8 bytes
var3=-2
var4=4294967294
One reason why var3 may end up with a different value than var4 is integer overflow. This happens when both multiplicands fit in an int, but the product doesn't.
Since ints and longs have different sizes on Arduino Uno*, the computation of var3 is different from computation of var4.
When you compute var3, the multiplication is done in longs on the initial values that fit in an int, so the result of multiplication is not translated. When you compute var4, the computation is done in ints, and then promoted to long. However, by then the result is already truncated, which results in the discrepancy that you are observing.
To make var4 the same correct value as var3, add a cast to long to one of the multiplicands, like this:
long var4 = (info->accelXYZ[0])*((long)info->taughtAccelXYZ[0]);
* int has 16 bits, while long has 32 bits.
Code in question:
std::stringstream cd;
int f = int((15 / allyCounter) * 100);
cd << f;
allyCounter is equal to 45. the idea is to get what percentage 15 is of allyCounter where allyCounter is a dynamic int that is constantly changing. i don't have much experience with c++ so I'm sure what I'm missing is something fundamental.
The problem here is almost certainly with integer vs. floating point math.
15/45 (when done in integer math) is 0.
Try
std::stringstream cd;
int f = int((15.0 / allyCounter) * 100);
cd << f;
...and see if things aren't better. 15.0 is a double precision floating point constant, so that'll force the math to be done in floating point instead of integers, so you'll get a percentage.
Another possibility would be to do the multiplication ahead of the division:
int f = 1500 / allyCounter;
If the numerator were a variable, this could lead to a problem from the numerator overflowing, but in this case we know it's a value that can't overflow.
In C++, 15 / 45 is 0. (It's called "integer division": the result of dividing two ints in C++ is also an int, and thus the real answer is truncated, and 15 / 45 is 0.)
If this is your issue, just make it a double before doing the division:
int f = static_cast<double>(15) / allyCounter * 100;
or even:
int f = 15. / allyCounter * 100;
(The . in 15. causes that to be a double.)
You are using integer division:
std::stringstream cd;
int f = int((15.0 / allyCounter) * 100);
cd << f;
The compiler sees 15/allyCounter and thinks it should return an integer (you passed it two integers, right?). 15/150 == 0 with integer division, you always round down. In this case the compiler sees 15.0 as a double, and uses decimal places.
float b = 1.0f;
int i = (int)b;
int& j = (int&)b;
cout << i << endl;
cout << j << end;
Then the output of i was 1, and the output of j was 1065353216! It is a big surprise to me! So what is the true meaning of (int&) conversion?
This is the problem with a C-style cast. You have to look closely to see what you're getting. In your case "(int)" was a normal static cast. The value is converted to an int via truncation. In your case "(int&)" was a reinterpret cast. The result is an lvalue that refers to the memory location of b but is treated as an int. It's actually a violation of the strict aliasing rules. So, don't be surprized if your code won't work anymore after turning on all optimizations.
Equivalent code with C++ style casts:
float b = 1.0f;
int i = static_cast<int>(b);
int& j = reinterpret_cast<int&>(b);
cout<<i<<endl;
cout<<j<<end;
Check your favorite C++ book on these kinds of casts.
In hexadecimal 1065353216 is 0x3F800000. If you interpret that as a 32-bit floating point number you get 1.0. If you write it out in binary you get this:
3 F 8 0 0 0 0 0
0011 1111 1000 0000 0000 0000 0000 0000
Or grouped differently:
0 01111111 00000000000000000000000
s eeeeeeee vvvvvvvvvvvvvvvvvvvvvvv
The first bit (s) is the sign bit, the next 8 bits (e) are the exponent, and the last 23 bits (v) are the significand. "The single precision binary floating-point exponent is encoded using an offset binary representation, with the zero offset being 127; also known as exponent bias in the IEEE 754 standard." Interpreting this you see that the sign is 0 (positive), the exponent is 0 (01111111b = 127, the "zero offset"), and the significand is 0. This gives you +00 which is 1.0.
Anyhow, what's happening is that you are taking a reference to a float (b) and reinterpreting it as an int reference (int&). So when you read the value of j you get the bits from b. Interpreted as a float those bits mean 1.0, but interpreted as an int those bits mean 1065353216.
For what it's worth, I have never used a cast using & like (int&). I would not expect to see this or use this in any normal C++ code.
float b = 1.0f;
...
int& j = (int&)b;
In the second conversion, you're looking at the memory space that contains b as if it was a memory space that contains an int. Floating point values are stored in a manner that's completely different as integers, so the results are really different...
In this particular case the conversion in question has no meaning. It is an attempt to reinterpret memory occupied by a float object and an int Lvalue. This is explicitly illegal in C/C++, meaning that it produces undefined behavior. Undefined behavior - that's the only meaning that it has in this case.
Seems like you are trying to create an int reference to a float by using (int&) cast. That will not work since floats are represented differently than int. This will not work.
If the representation of float and int are same then it might have worked.
What were you going to do?
The same thing:
float b = 1.0f;
int i = (int) b;
int* j = (int*)b;//here we treat b as a pointer to an integer
cout<<i<<endl;
cout<<(*j)<<endl;
How to fix:
float b = 1.0f;
int i = (int) b;
int castedB = (int)b;//static_cast<int>(b);
int& j = castedB;
cout<<i<<endl;
cout<<j<<endl;