查找奇数平方和时遇到麻烦

Trouble finding sum of odd integers cubed

本文关键字:遇到 麻烦 查找      更新时间:2023-10-16

尝试了几次,但仍然没有找到我的错误:这是我的程序。 我需要从 1 和整数 x 中找到奇数,并找到它们的立方之和。

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;

return 0;
}

至少,您应该将while中的
比较从
while (i > n)
更改为
while (i <= n)

有许多数字i将大于输入的数字,n.

您没有为 while 循环添加大括号。

while (i > x)
if (i%2 == 0) {}

需要:

while (i > x){
if (i % 2 == 0) {}
}

另外,你在那个if语句里面做什么? 您应该递减 x,以查找每个数字是否为奇数。

另外,你的程序提前结束,因为i是1,如果用户输入一个大于1的数字,你的while循环甚至不会运行。 你告诉 while 循环仅在 i 大于 x 时运行。 尝试将其更改为小于:

从:

while (i > x){

自:

while (i < x){

另外,你没有对x做任何事情。 你想递减 x,而不是加 i。 虽然,我建议使用do-while循环。(dowhile 循环在增量之前先进行一次迭代(

do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this 
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.  
temp = pow(x,3); 
//you don't want to take the power of the added sum, 
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power.  So here we have temp, a 
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--;  //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar 
<< " = " << result << endl;
return 0;
}

注意:if-else 语句用于流量控制,它就像 true 和 false,一个或另一个,以便您的数据将流向某个地方。 我使用了两个 if 语句,因为我想完全控制流。

注意2:可以使用:

using namespace std;

起初,但最终您想开始了解每个命令正在使用的库。 当您进入更复杂的编程时,您开始使用来自不同库的命令,而不是标准库。