繁体   English   中英

如何添加升序数组中的所有值?

[英]How do i add all the values in my ascending array?

首先,我需要将数组的所有值重新排列为升序,然后再添加。 例如,用户输入 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();
}
   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;
    }
  }

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

我不得不同意其他评论员的意见,即您的编码风格不是首选,但故事中可能有更多的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM