【发布时间】:2017-01-24 02:44:28
【问题描述】:
首先,我需要将数组的所有值重新排列为升序,然后再添加。例如,用户输入 9 2 6,它会先按升序显示(2 6 9),然后再添加总和 2 8 17.. 问题是我的升序不起作用,我的代码有问题吗?
#include <iostream>
#include<conio.h>
using namespace std;
int numberof_array, value[10], temp;
int i = 0, j;
void input()
{
cout << "Enter number of array:";
cin >> numberof_array;
for (i = 0; i < numberof_array; i++)
{
cout << "Enter value for array [" << i + 1 << "] - ";
cin >> value[i];
cout << endl;
}
}
void computation()
{
// this is where i'll put all the computation
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
for (i = 0; i <= numberof_array; i++)
{
for (j = 0; j <= numberof_array - i; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j];
value[j] = value[j + 1];
value[j + 1] = temp;
}
}
}
}
void display()
{
// display all the computation i've got
cout << "\nData after sorting: ";
for (j = 0; j < numberof_array; j++)
{
cout << value[j];
}
getch();
}
int main()
{
input();
computation();
display();
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
如果没有产生想要的结果,那么你的代码显然有问题。
-
此外,所有这些全局变量
<conio.h>和完全没用的函数名称computation是怎么回事?你需要找到更好的学习材料。 -
你为什么使用 C 风格的数组而不是
std::vector<int>?然后您可以停止手动排序,只需使用std::sort(values.begin(), values.end());
标签: c++ arrays conditional