【问题标题】:ARRAY - Delete max negative elementARRAY - 删除最大负元素
【发布时间】:2013-11-16 12:22:26
【问题描述】:

任务: 给定一个数组 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;
}

【问题讨论】:

  • 它已经完成了它应该做的事情。它显示 -8 是数组中的最小元素。你想在新创建的数组中找到最小的数字吗?
  • @user2699298 再次阅读问题。代码没有做它应该做的事情。

标签: c++ arrays for-loop


【解决方案1】:

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

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

尝试访问数组之外​​的内存。

此外,变量的名称与其含义不符。例如在这个循环中

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

}

搜索最小元素,但将包含最小值的变量的名称是 nmaxelement。

还要考虑到数组不能有负元素。

【讨论】:

    【解决方案2】:

    由于这是一个学习练习,我不会写代码,只是解释:

    • 一般来说,数组不保证有负元素。因此,程序应该准备好看到两种结果 - (a) 当至少有一个负元素时,您可以产生所需的输出,以及 (b) 当数组中没有负元素时。
    • 牢记上述内容,您的第二个循环需要保留当前状态的两个部分:您已经拥有的 nmaxelement 和您需要引入的 bool haveNegatives
    • 在第二个循环之前将 haveNegatives 设置为 `false
    • 在循环内部,首先检查数字c[i] 是否为负数。如果它是非负数,则转到下一个元素(例如,使用 continue 语句)。
    • 如果数字c[i]为负数,查看haveNegatives的当前值:如果设置为true,比较c[i]nmaxelement,如果是则更改nmaxelement的当前值c[i] 更大。
    • 如果haveNegativesfalse,则将其设置为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;
    }
    

    【讨论】:

    • 你能给我更多关于布尔的信息吗?
    • @Sofie 这是一种允许您存储逻辑表达式值的类型 - truefalse。如果您还没有研究过bools,请考虑使用maxNegativeIndex 替换haveNegativesnmaxelement 的替代方法。
    • @Sofie 你试过了吗?进展如何?
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2020-12-28
    • 2013-12-10
    • 1970-01-01
    • 2014-07-30
    相关资源
    最近更新 更多