Solved

Floats

Posted on 1998-08-27
5
301 Views
Last Modified: 2012-05-04
Hi,

I'm using Visual J++,
and I can't seem to get floats working right!
Here's a piece of code:
float f = 150 / 255;
g.drawString(new Float(f).toString,10,10);

It says 0.0
I'm no mathematician but I'm pretty sure that 150/255 isn't 0.

What's wrong?

Thanks
0
Comment
Question by:BabyFace
  • 4
5 Comments
 
LVL 3

Accepted Solution

by:
sailwind earned 30 total points
ID: 1222768
150 and 255 are both integers.
When you divide two integers, you'll get an integer.
0.588 casted into an integer is a 0. That's why you're
getting 0 for output.

You should do:

float f = 150.0/255.0;   // now you're dividing float by float

That'll correct the problem.

0
 
LVL 3

Expert Comment

by:sailwind
ID: 1222769
Oh yeah, since 150.0 is considered a double in Java. You should do:

double d = 150.0/255.0  


0
 
LVL 1

Author Comment

by:BabyFace
ID: 1222770
Thanks for your answer.
Which of the two take up more mem?
I suppose it's double eh?

Thanks again.
0
 
LVL 3

Expert Comment

by:sailwind
ID: 1222771
int 32 bits
double 64 bits
0
 
LVL 3

Expert Comment

by:sailwind
ID: 1222772
float 32 bits
long 64 bits
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now