Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
September 10th, 2012, 08:23 AM
 x.sophie.x
Registered User

Join Date: Aug 2012
Location: Bristol
Posts: 13
Time spent in forums: 2 h 14 m 32 sec
Reputation Power: 0
Do while loops

Here is the start of the task put to me:

1: Create two random numbers x and y which are between +1 and -1. To do this just double the
random number (which is between 0 and 1) and subtract 1.
2: calculate: z=x^2+y^2
3: Repeat 1 and 2 until z<1.0 using, for example, a while(){} loop.

This is what I've come up with, it runs no problem but doesn't print a result to screen. (At least not in my attention span.) Am I doing something wrong here?

Code:
```#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
double x,y,
z; i=0;

{ x=(((rand()/(double)RAND_MAX)*2)-1);//generates a pseudo-random number between +1 and -1
y=(((rand()/(double)RAND_MAX)*2)-1);//generates a pseudo-random number between +1 and -1

do
{
z= ((x*x)+(y*y));//squares the two pseudo-random numbers and adds the squares together i++; }

while(z>1);
printf("%lf\n",z);//prints the result z to screen }

return 0; }```

#2
September 10th, 2012, 10:17 AM
 MrFujin
Lord of the Dance

Join Date: Oct 2003
Posts: 3,343
Time spent in forums: 2 Months 2 Weeks 4 Days 17 h 11 m 24 sec
Reputation Power: 1828
Look at you condition for z, you have z>1 but it should be z<1.

Part 1 (creating number) is before the loop, should be included.

#3
September 10th, 2012, 10:27 AM
 EEmaestro
Contributing User

Join Date: Apr 2012
Posts: 59
Time spent in forums: 1 Day 18 h 13 m 7 sec
Reputation Power: 2
The first thing you should do is compile it. If it doesn't compile, then you have to critically examine the syntax of each statement and ask yourself (1) what is the proper syntax and (2) does this line have every element of proper syntax ?

Two easy checks are (1) Count the number of open-braces "{" and close-braces "}" in your program. They must be the same.
(2) Do the same thing for open-paren's "(" and close-paren's ")".

#4
September 12th, 2012, 04:13 AM
 x.sophie.x
Registered User

Join Date: Aug 2012
Location: Bristol
Posts: 13
Time spent in forums: 2 h 14 m 32 sec
Reputation Power: 0
Quote:
 Originally Posted by EEmaestro The first thing you should do is compile it. If it doesn't compile, then you have to critically examine the syntax of each statement and ask yourself (1) what is the proper syntax and (2) does this line have every element of proper syntax ? Two easy checks are (1) Count the number of open-braces "{" and close-braces "}" in your program. They must be the same. (2) Do the same thing for open-paren's "(" and close-paren's ")".

Thanks guys! Fixed it!

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Do while loops