【发布时间】:2018-03-18 19:26:49
【问题描述】:
这个程序正在运行,但我正在寻找一种更有效的方式来运行这个程序。 你可以看到我注释掉了代码,因为我认为它可以在没有额外代码的情况下运行。但是,我有点困惑。 在 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;
}
【问题讨论】:
-
你认为
if (x = 9)是做什么的?如果你明白它的作用,你为什么要使用if?此外,听起来您的目标是找到x和y的所有组合,其中两者都是从 0 到 8 的整数,包括 0 到 8,以求解给定的方程。你可以用简单的代数做到这一点。 -
一堆
if (x == #)语句可能应该替换为switch(x) -
你为什么贴这么多被注释掉的代码?
-
if (x = 9) ...与 C++ 或 Java 或大多数其他现代计算机语言中的if (x == 9) ...不同。当你明白这一点时,你就会有一个良好的开端...... -
阅读一本好的 C++ 编程书籍。编译所有警告和调试信息:
g++ -Wall -Wextra -g和 GCC。改进代码以获得没有警告。使用调试器gdb
标签: c++ computer-science