简体   繁体   中英

Working with “for-loops”

I am learning Java using "Java how to program" (Deitel and Deitel). Right now I´m stuck solving an exercise that wants me to print out a table with all possible values of "pythagoran tripples" under 500. I am supposed to use a nested "for-loop" to check all possibilities. In other words: a, b, and c has to be integers. The following expression has to be true: a2 + b2 = c2, and the program should print a table with all possible combinations ( with c < 500 ). I just can´t figure this out. Can anyone please help me? My code, which only prints out the first combination ( 3 4 5 ) is as follows:

    public class Pythagoras 
            {
        public static void main(String[] args) 
            {

            for (int a = 3, b = 4, c = 5; (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) && (c <= 500); c++)
        {
        System.out.printf("%d %20d %20d", a, b, c);
        }

        }

    }

Your code only prints 3 4 5 because it only runs 1 iteration of the for loop. In your for loop, you enlarge c each iteration, but you don't change a and b. That means that after the first iteration, it will evaluate 3^2 + 4^2 == 6^2 , which returns false and it thus exits the for loop.

To solve this, you could use three nested for loops like this:

for(int a = 1; a < 500; a++){
   for(int b = 1; b < 500;b++){
       for(int c = 1; c < 500;c++){
           if(Math.pow(c,2) == Math.pow(a,2) + Math.pow(b,2){
                // code execution
           }
       }
   }
}

As you noted you should have nested loops, ie for each variable a , b and c you should have a separate loop testing all possible values:

for(int a = 1; a <= 500; a++) {
  for(int b = 1; b <= 500; b++) {
    for(int c = 1; c <= 500; c++) {
      ...
    }
  }
}

Next you have a condition which you test inside your loop (ie where the ... ) is. Do not confuse your output-condition with the loop-condition (when the loop terminates).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM