C ++编程更有效的方法

时间:2017-10-06 23:06:03

标签: c++ computer-science

此程序正在运行,但我正在寻找一种更有效的方式来运行此程序。 您可以看到我注释掉了代码,因为我认为没有额外的代码就可以解决问题。但是,我有点困惑。 在else语句中,我试图递减x值,使其变为x = 8并再次运行循环并再次递减。 但它没有用。 任何人都可以帮我,我该怎么办?谢谢。

#include <iostream>

#include <cmath>

using namespace std;

int main()
{
    int x, y;

    if (x = 9) {
        for (y = 0; y < 9; y++)
            if (3 * pow (x, 2) + 4* pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
            else {
                x--;

            }
    }
    /*   if (x = 8) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 7) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 6) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 5) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 4) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 3) {
         for (y = 0; y < 9; y++)
             if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                 cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 2) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout << "x value is : " << x << endl << "y value is: " << y<<endl;
    }
     if (x = 1) {
        for (y = 0; y < 9; y++)
            if (3 * pow(x, 2) + 4 * pow(y, 2) == 271)
                cout <<"x value is : "<< x <<endl<<"y value is: "<< y<<endl;
    }

    */

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

只需使用for循环迭代x

的值
for (x = 9; x > 0; x--) {
    for (y = 0; y < 9; y++) {
        if (3 * pow (x, 2) + 4* pow(y, 2) == 271) {
            cout << "x: " << x << endl << "y: " << y << endl;
        }
    }
}