• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

How to write a program using this statement, int n = (int)Math.floor(Math.random()*100000+1);?

Math
How to write a program using this statement, int n = (int)Math.floor(Math.random()*100000+1);?



lass GuessingGame {  

     public static void main(String[] args) {      

         int n = (int)Math.floor(Math.random()*100000+1);  

         int sum = 0;  

         int digit;  

         number = x;  

         digit = x % 10;  

         sum += digit;  

         x = x/10;  

         digit = x % 10;  

         sum += digit;  

         x = x/10;  

         digit = x % 10;  

         sum += digit;  

         x = x/10;  

         digit = x % 10;  

         sum += digit;  

         System.out.println("Given number= "+number+"; sum of digits = "+sum);  

     }  

 }
0
waltbaby315
Asked:
waltbaby315
1 Solution
 
waltbaby315Author Commented:
hi
0
 
TBK-ConsultingCommented:
what exactly are you trying to accomplish?  Have the computer guess a number that the user randomly chose between 1 and 100,000??? if so - I'd have it do the following - (pseudo-coded as I am not good with languages)

Get Random Number between 2 and 100,000 and store in Guess
Set Low Guess = 0
Set High Guess = 100001
Start Loop
     Ask User if Guess is correct and ask for lower or higher
     If higher
          move guess to low guess
          if guess + 100 <  high guess
               add 100 to guess goto start loop
          else if guess +10 < high guess
              add 10 to guess goto start loop
              else add 1 to guess goto start loop
     if lower
          move guess to high guess
          if guess - 100 > low guess
               subtract 100 from guess goto start loop
          else if guess - 10 > low guess
               subtract 10 from guess goto start loop
               else subtract 1 from guess goto start loop
End Loop


NOTE - the more nested if's you put in the faster the program should get to the correct number.
0
 
TommySzalapskiCommented:
Your program is fine (well, it has errors), but you should really use a loop. Like this:
   public static void main(String[] args) 
   {      
 
         int n = (int)Math.floor(Math.random()*100000+1);  

         int sum = 0;  

         int digit;  

         int x = n;  

         while(x > 0)
         {
            digit = x % 10;  
            x /= 10;
            sum += digit;  
         }
         System.out.println("Given number= "+number+"; sum of digits = "+sum);  

     }  

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now