【问题标题】:User is entering 10 numbers, find max negative value and its index/position用户正在输入 10 个数字,找到最大负值及其索引/位置
【发布时间】:2015-10-28 05:32:01
【问题描述】:

用户正在输入 10 个数字,找到最大负值及其索引/位置。

ps:必须使用“for”。 帮助请-_-”

这是我的代码:

#include <iostream>

using namespace std;

int main() {

    double value, maxValue, index;

    cin >> value;
    maxValue = value;
    index = 1;

    for (int i = 2; i <= 10; i++) {
        cin >> value;

        if (value > maxValue&&value<0) {
            maxValue = value;
                index = i;
        }

    }
    cout << "Max value = " << maxValue << " index = " << index << endl;


}

【问题讨论】:

  • 我知道您尝试了什么,但是您在使用代码时遇到了什么问题?
  • 问题出在哪里?
  • max negative value 是什么意思?最大绝对值为负数,或最接近0 的负数(所以-42-1 之间的哪一个)
  • 你还没有检查第一个值是否为负,现在假设用户只输入了非负数...

标签: c++ for-loop


【解决方案1】:

换行

if (value < maxValue && value<0)

【讨论】:

    【解决方案2】:

    这是我想出的解决方案:

    #include <iostream>
    
    using namespace std;
    
    int main() {
        double maxValue;
        int index = -1;
    
        for (int i = 0; i < 10; i++) {
            double value;
            cin >> value;
            if(!(value < 0)) {
                continue;
            }
            if(index >= 0) {
                if(value > maxValue) {
                    maxValue = value;
                    index = i;
                }
            } else {
                maxValue = value;
                index = i;
            }
        }
        if (index >= 0) {
            cout << "Greatest negative value is " << maxValue << " at index " << (index+1) << endl;
        } else {
            cout << "No negative value issued" << endl;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-13
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      相关资源
      最近更新 更多