使用毕达哥拉斯tripple应用程序生成编译错误的嵌套forloop

时间:2015-05-16 10:56:50

标签: java pythagorean

这是我的代码:

     //a java application prints out all values of pythagorean triples     that        range from 1 to 500. 
      //uses a trippled nested for loop
    public class pythagoreantriples{

        //main method executes java application

        public static void main(String args[]){

       //declare variables


    for(int side_1=3;  side_1 <=500;  side_1++){

       for(int side_2=4; side_2 <=500; side_2++){

            for(int hypo=5; hypo <=500; hypo++){



                Math.pow(hypo,2)=Math.pow(side_1,2)+Math.pow(side_2,2);

                System.out.printf("n/%d/n",     Math.pow(side_1,2),"                 ", Math.pow(side_2,2),"                     ", Math.pow(hypo,2));



    } //end first for loop

    }//end second for loop

    } //end third for loop

    }//end main

    }//end class

以下是我尝试编译代码时生成的错误:

>C:\Users\Courtney\Desktop\chapter five exercises for      >java\pythagoreantriples.java:17: error: unexpected type
            hypo*hypo=side_1*side_1+side_2*side_2;
                ^
  >required: variable
>found:    value
>C:\Users\Courtney\Desktop\chapter five exercises for 

>java\pythagoreantriples.java:19: error: unexpected type




  >Math.pow(hypo,2)=Math.pow(side_1,2)+Math.pow(side_2,2);
                ^
  >required: variable
  >found:    value
  >2 errors

  >Tool completed with exit code 1

我做错了什么?它应该打印出一张毕达哥拉斯三胞胎的表格,范围从1到500.当然,forloop应该打印的第一个毕达哥拉斯三重奏是3 ^ 2 + 4 ^ 2 = 5 ^ 2

1 个答案:

答案 0 :(得分:0)

您应该将失败的语句更改为条件表达式,将=替换为==,并在if语句中使用它,以决定是否打印当前的三元组:

if (Math.pow(hypo, 2) == Math.pow(side_1, 2) + Math.pow(side_2, 2))

您还需要处理打印输出。 Math.pow的结果是double,而不是int。无论如何,你应该打印边,而不是正方形。