查找立方的奇数整数之和的问题

时间:2018-10-16 20:49:16

标签: c++ arrays loops for-loop while-loop

尝试了几次,但仍然没有发现我的错误:这是我的程序。我需要从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;

}

2 个答案:

答案 0 :(得分:2)

至少,您应该在$payment_gateway中更改比较值
来自
  while

  while (i > n)

有很多数字,while (i <= n)会比输入的数字i大。

答案 1 :(得分:-1)

您没有在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语句用于流控制,就像对与错一样(一个或另一个),因此您的数据将在某个地方流动。我使用了两个if语句,因为我想完全控制流。

note2:可以使用:

 using namespace std;
首先是

,但最终您想开始学习每个命令正在使用的库。当您进入更复杂的编程时,您开始使用与标准库不同的库中的命令。