C++ 数组-删除最大负元素

C++ 数组-删除最大负元素,c++,arrays,for-loop,C++,Arrays,For Loop,任务:给它一个数组C(15)。从数组中删除最大负元素。写下它的索引。显示初始数组和更改的数组 注意:此代码写入最小的负元素,即数组中的“-8” 需要帮助:我需要更改一些内容,它将写入数组中最大的负元素,即“-5” #include <iostream> using namespace std; int main() { int c[15]= { 1, 2, 3, 4, 5, 6, -5, 8, 9 , 10, -7, 12, -8, 14, 15}; int nmaxelemen

任务:给它一个数组C(15)。从数组中删除最大负元素。写下它的索引。显示初始数组和更改的数组

注意:此代码写入最小的负元素,即数组中的“-8”

需要帮助:我需要更改一些内容,它将写入数组中最大的负元素,即“-5”

#include <iostream>

using namespace std;

int main()
{
int c[15]= { 1, 2, 3, 4, 5, 6, -5, 8, 9 , 10, -7, 12, -8, 14, 15};
int nmaxelement = c[0];
int nmaxelementplace;
int i;

cout<<"The array is: \n";
for (i=0; i<15; i++)
{
    cout<<c[i]<<" ";
}

for (int i=0; i<15; i++)
if (c[i]<nmaxelement)
{
     nmaxelement = c[i];
            nmaxelementplace = i;
}


cout<<"\nNegative max element is "<<nmaxelement<<endl;
cout<<"Its place: "<<nmaxelementplace<<endl;

int k=nmaxelementplace;
int n=15;

cout<<"Array with the deleted element: "<<endl;

for (int i=k; i<n; i++)
    c[i]=c[i+1];
    n=n-1;
for (int i=0; i<n; i++)
cout<<c[i]<<" ";


return 0;
}
#包括
使用名称空间std;
int main()
{
int c[15]={1,2,3,4,5,6,-5,8,9,10,-7,12,-8,14,15};
int nmaxelement=c[0];
int-nmaxelementplace;
int i;

cout因为这是一个学习练习,所以我不会编写代码,只是解释一下:

  • 通常情况下,不能保证数组中有负元素。因此,程序应该准备好看到两种结果—(a)当至少有一个负元素时,您可以生成所需的输出;以及(b)当数组中没有负元素时
  • 记住以上内容,第二个循环需要保留当前状态的两部分:已经存在的
    nmaxelement
    ,以及需要引入的
    bool haveNegatives
  • 在第二个循环之前,将haveNegatives设置为'false'
  • 在循环内部,首先检查数字
    c[i]
    是否为负数。如果为非负数,则转到下一个元素(例如,使用
    continue
    语句)
  • 如果数字
    c[i]
    为负数,查看
    haveNegatives
    的当前值:如果设置为
    true
    ,将
    c[i]
    nmaxelement
    进行比较,如果
    c[i]
    较大,则更改
    nmaxelement
    的当前值
  • 如果
    haveNegatives
    false
    ,则将其设置为
    true
    ,并将
    haveNegatives
    设置为
    c[i]
循环结束时,如果
nmaxelement
包含数组的最高负数元素,则
haveNegatives
将设置为
true
;如果数组中没有负数,
nmaxelement
将保持
false

或者,您可以将当前最大负值的索引存储在单个变量中,而不是同时保留值和索引。在这种情况下,您可以在循环之前将该索引设置为
-1
,并对该索引设置条件,如下所示:

// Come to this point only when c[i] is negative
if (maxNegativeIndex == -1 || c[i] > c[maxNegativeIndex]) {
    maxNegativeIndex = i;
}

您显示的代码包含几个错误。例如,变量nmaxelementplace未初始化, 这个环路

for (int i=k; i<n; i++)
    c[i]=c[i+1];

用于(int i=k;iIt已经做了它应该做的。它显示了数组中最小的元素-8。你想在新创建的数组中找到最小的数字吗?@user2699298再次阅读这个问题。代码没有做它应该做的。你能给我更多关于bool的信息吗?@Sofie它是一种允许你存储逻辑数组值的类型表达式->代码>真< /代码>或代码> false < /代码>。如果您还没有学习“代码> BoOL  s,请考虑使用另一种方法,使用<代码> Max NealTiVeDige<代码>替换“<代码> HaveGeave< <代码>和<代码> nMax元素< /代码>。@索菲,你尝试过了吗?它进展如何?
for (int i=0; i<15; i++)
if (c[i]<nmaxelement)
{
     nmaxelement = c[i];
            nmaxelementplace = i;