I am trying to use java to divide a variable number inside a for loop by 3. For some reason it always has only one number after the decimal and it is always a 0. for what I am trying to do I need to know if 3 goes into it evenly so the numbers after the decimal are important for the algorithm I have made. I have tried using the variable types (double) & (float)
Note: Please do not suggest another way of finding if three goes evenly into something because 1) I may need to work with decimals in the future in which case this question is important for me to have answered. 2) this is for project euler and i would like to work out how to do things on my own; I'm only asking this because I'm confused with an aspect of the language not how to solve the problem. If my way is wrong I will discover it on my own and work out how to do it myself.
Thanks
~Zero
division problem?
Started by zeroradius, Oct 10 2010 07:13 AM
3 replies to this topic
#1
Posted 10 October 2010 - 07:13 AM
|
|
|
#2
Posted 10 October 2010 - 07:52 AM
I'm only getting a zero as only decimal if i do int / int. (Ideone.com | 3TDo2)
output:
double dNumber = 5.0;
double dThree = 3.0;
int iThree = 3;
int iNumber = 5;
double result = dNumber / iThree ;
System.out.println("double/int: " + result);
result = iNumber / dThree ;
System.out.println("int/double: " + result);
result = dNumber/ dThree;
System.out.println("double/double: " + result);
result = iNumber/ iThree;
System.out.println("int/int: " + result);
output:
double/int: 1.6666666666666667 int/double: 1.6666666666666667 double/double: 1.6666666666666667 int/int: 1.0
#3
Posted 10 October 2010 - 07:57 AM
Your description of the problem is too vague for us to guess what is going wrong without a sample code. An explicit integer cast after integer devision will do this (such as what oxano mentioned), which leads us to believe you hadn't casted it properly somewhere.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
#4
Posted 10 October 2010 - 08:31 AM
that fixed it. I had set a double type variable to hold i/3 but i had set i as an int rather than a double. (>.<) My first time using a strongly typed language and doing math programmicly I usually just do data retrieval and writing. Sorry to waste your time and i should have posted the code, I forgot as i'm trying to get ready for work. thanks for the help. +rep
wont let me rep Null. Guess i can only give it one of you.
wont let me rep Null. Guess i can only give it one of you.


Sign In
Create Account


Back to top









