C++ x 不循环递增

C++ x doesnt loop increament

老师给我布置了一个任务,比如: x^2 + y^3 = z

x只填奇数 y 只填充 even

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;
int x,y,z;

int main(){
   for (x=1;x<=20;x++){
      if ((x%2==1)&&(y%2==0)){
         for (y=1;y<=20;y++){
            if ((x%2==1)&&(y%2==0)){
               z = (x*x) + (y*y*y);
               cout << "x^2 + y^3 =" <<z <<"\n";
            }
         }
      }
   }
}

我尝试像上面那样编写自己的代码,但是唯一的一个循环是 Y,x 仍然是 1。

我也想让 x 循环播放。我应该怎么办?

我的输出期望是:

1^2 + 2^3 = 9
3^2 + 4^3 = 71
5^2 + 6^3 = 241
7^2 + 8^3 = 561
9^2 + 10^3 = 1081
11^2 + 12^3 = 1849
13^2 + 14^3 = 2913
15^2 + 16^3 = 4321
17^2 + 18^3 = 6121
19^2 + 20^3 = 8361

PS。抱歉我的英语不好 :D

这是你拥有的:

int main(){
   for (x=1;x<=20;x++){
      if ((x%2==1)&&(y%2==0)){
         for (y=1;y<=20;y++){
            if ((x%2==1)&&(y%2==0)){
               z = (x*x) + (y*y*y);
               cout << "x^2 + y^3 =" <<z <<"\n";
            }
         }
      }
   }
}

问题是第一个if ((x%2==1)&&(y%2==0)){检查。

内部for循环完成后,y的值为21。因此,无论x的值是多少,上述条件的计算结果都是false。因此,内部 for 循环只执行一次。您需要删除第一个 if 语句。

int main(){
   for (x=1;x<=20;x++){
      for (y=1;y<=20;y++){
         if ((x%2==1)&&(y%2==0)){
            z = (x*x) + (y*y*y);
            cout << "x^2 + y^3 =" <<z <<"\n";
         }
      }
   }
}

更新,回应OP的评论

看来您需要更简单的代码。

int main(){

   // Start with x = 1 and increment x by 2. It will be always be odd 
   for ( x = 1; x <= 20; x += 2 ){

      // No need to create another loop. y is simply x+1
      // Since x is odd, y will be even.
      y = x+1;

      // Compute the result and print it.
      z = (x*x) + (y*y*y);
      cout << "x^2 + y^3 =" << z <<"\n";
   }
}

因为 y = 21 在里面 y loop.So 之后不会执行 x 循环。希望对你有帮助。