【问题标题】:How do i add all the values in my ascending array?如何在升序数组中添加所有值?
【发布时间】: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 示例,以及您在调试器中所做的观察。
  • 如果没有产生想要的结果,那么你的代码显然有问题。
  • 此外,所有这些全局变量 &lt;conio.h&gt; 和完全没用的函数名称 computation 是怎么回事?你需要找到更好的学习材料。
  • 你为什么使用 C 风格的数组而不是 std::vector&lt;int&gt;?然后您可以停止手动排序,只需使用std::sort(values.begin(), values.end());

标签: c++ arrays conditional


【解决方案1】:
   void computation(){
    for (int j = 0; j < numberof_array; j++)  cout << value[j]<<"\t";

    for (int i = 0; i <= numberof_array; i++) {
        temp = value[i];
        int temp_idx = i;
        for (int j = i; j < numberof_array; j++) {
            if (value[j] < temp) {
                temp = value[j];
                temp_idx = j;
            }
        }
        int temp_swap = value[i];
        value[i] = value[temp_idx];
        value[temp_idx] = temp_swap;
    }
  }

如何将您的第二个功能更改为上述内容。

我必须同意其他评论员的观点,即您的编码风格不是首选,但故事可能比表面上看到的要多。

【讨论】:

    猜你喜欢
    • 2014-11-01
    • 2011-02-20
    • 2022-11-05
    • 2021-06-22
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    相关资源
    最近更新 更多