查找奇数平方和时遇到麻烦
Trouble finding sum of odd integers cubed
尝试了几次,但仍然没有找到我的错误:这是我的程序。 我需要从 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;
起初,但最终您想开始了解每个命令正在使用的库。 当您进入更复杂的编程时,您开始使用来自不同库的命令,而不是标准库。
相关文章:
- 查找奇数平方和时遇到麻烦
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- MySQL 从注入过渡到参数化时遇到麻烦
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 以分类方式插入节点时遇到麻烦
- 在此任务上遇到麻烦,我们需要使用指针和数组来找到文本文件中某些数字的平均值,中值和模式
- 我在DFS搜索(树)代码中遇到麻烦.我如何打破递归
- 我在处理字符时遇到麻烦
- 在我的代码覆盖本身时遇到麻烦,我不确定为什么
- C++处理文件,在制作程序时遇到麻烦
- 在客户端/服务器计算器C 方面遇到麻烦
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- boost :: phoenix ::功能遇到麻烦
- 在具有模板成员功能的模板类方面遇到麻烦
- 通过模板参数遇到麻烦
- 快速排序在C++,遇到麻烦
- 计算字符时遇到麻烦
- 在C++中摸索多个排他性组合时遇到麻烦
- 编译phash程序时遇到麻烦
- 在 Linux 上为 OpenGL 4.2 设置开发环境(查找 gl.h 时遇到麻烦)