数组 - 空,正元素的数量和正元素的总和

ARRAY - null, positive elements' amount and positive elements' summation

本文关键字:元素 数组      更新时间:2023-10-16

我试图编写代码但卡住了...

任务是:给定整数的数组 C(15)。求零、正元素的数量和正元素的总和。找到的含义放在数组的中间。显示初始数组和更改的数组。

#include <iostream>
using namespace std;
int main()
{
int array1[15]={-1, 0, -3, -2, 3, 4, 1, 2, 5, 6, -5, -4, 7, 8, 9};
int maxarray=array1[0];
int maxarrayplace;
int minarray=0;

//1
for (int inindex=0; inindex<15; inindex++)
{
    int minindex=inindex;
        for (int preindex=inindex+1; preindex<15; preindex++)
        {
            if (array1[preindex]<array1[minindex])
            minindex=preindex;
        }
        swap(array1[inindex], array1[minindex]);
}
cout<<"Array1 is "<<array1[15];
for (int i=0; i<15; i++)
{
    cout<<array1[i]<<" ";
}
//2

cout<<"nPositive numbers: n";
for (int i=0; i<15; i++)
if (array1[i]>minarray)
{
    cout<<array1[i]<<" ";
}
//positive element's amount




 return 0;
 }

首先是代码中的这一行:

cout<<"Array1 is "<<array1[15];

不正确,当数组大小为 15 时,不能使用索引 15,最后一个元素索引为 14。使用索引 15 应该会给出"越界"异常。

另外,如果要显示正数,

只需将它们与零进行比较,下面的代码还将显示正数的数量和总和:

cout<<"nPositive numbers: n";
int amount = 0;
int sum = 0;
for (int i=0; i<15; i++)
 if (array1[i]>0)
 {
    cout<<array1[i]<<" ";
    amount++;
    sum += array1[i];
 }
cout<<"The amount of the positive numbers is : "<<amount<<"n";
cout<<"The summation of the positive numbers is : "<<sum<<"n";

如果这不是您要找的,请更清楚地解释。