Quantcast

Jump to content


Photo

[Java] Double


  • Please log in to reply
7 replies to this topic

#1 Rambo

Rambo
  • 833 posts

Posted 16 February 2010 - 01:12 AM

Write a for loop which uses an iteration variable of type double. This should start with a value of 0.5, iterate by steps of 0.3 until the iteration variable exceeds 2. Run the loop, maybe using the CodePad. What is produced? Explain why. Hint: how are floating point ('real') numbers stored?


Help :|


#2 Dan

Dan
  • Resident Know-It-All

  • 6382 posts


Users Awards

Posted 16 February 2010 - 03:15 AM

for (double d = 0.5; d < 2; d += 0.3)
{
	//Console.WriteLine(d);  // C#
	System.out.println(d); // Java
}

Is your for loop.

Run it, see what results you get. Refer to Floating Point to figure out why you're getting what values you're getting.

#3 Waser Lave

Waser Lave

  • 25516 posts


Users Awards

Posted 16 February 2010 - 04:12 AM

for (double d = 0.5; d < 2; d += 0.3)
{
	//Console.WriteLine(d);  // C#
	System.out.println(d); // Java
}

Is your for loop.

Run it, see what results you get. Refer to Floating Point to figure out why you're getting what values you're getting.


Technically you should probably do <= 2 because they ask for the loop to run until it exceeds 2.

#4 Dan

Dan
  • Resident Know-It-All

  • 6382 posts


Users Awards

Posted 16 February 2010 - 05:52 AM

Technically you should probably do <= 2 because they ask for the loop to run until it exceeds 2.


Ah well spotted. Right you are.

#5 Rambo

Rambo
  • 833 posts

Posted 18 February 2010 - 02:12 AM

Kinda having trouble explaining this, could anyone help?



#6 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 18 February 2010 - 02:19 AM

I ran something very similar in C++:
#include <iostream>

using namespace std;

void main(void)
{
	for(double d=0.5; d <= 2.0; d+=0.3)
	{
		cout << d << endl;
	}
}

the out put is:
0.5
0.8
1.1
1.4
1.7
2


What's to explain about it?

#7 Rambo

Rambo
  • 833 posts

Posted 18 February 2010 - 02:27 AM

It goes up in .3



#8 Melchoire

Melchoire
  • 5284 posts


Users Awards

Posted 18 February 2010 - 02:22 PM

I don't get the point of that hint that they give you.


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users