【发布时间】:2019-03-21 11:34:03
【问题描述】:
尝试了几次,但仍然没有找到我的错误:这是我的程序。我需要从 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;
}
【问题讨论】:
-
首先,你应该避开
using namespace std,其次,看看while(i > x),你好像漏掉了什么。 -
也许要获得奇数,您可以考虑一个从 1 开始并以 2 递增的
for()循环。例如:for (i=1; i<x; i+=2)那么您应该只有i的奇数。 -
顺便说一句,
pow函数是浮点数并返回浮点数。乘法效率更高,例如i * i * i. -
您可以通过否定条件来跳过
if中的空代码,例如if ((i%2) != 0) { result = i * i * i; ++i}
标签: c++ arrays loops for-loop while-loop