【问题标题】:how to get correct answer merge 2 sorted arrays?! C++ [closed]如何获得正确答案合并 2 个排序数组?! C++ [关闭]
【发布时间】:2014-03-15 21:36:48
【问题描述】:

我写了一个小算法,用于将 marge 转换为有序数组。但我有问题。

#include <iostream>
using namespace std;

int main() {

    // main function started form here:

    int firstArray[10] = {1,3,5,7,9,11,13,15,17,19};
    int secondtArray[10] = {2,4,6,8,10,12,14,16,18,20};

    int mergedArray[20];
    int firstCounter=0 , secondtCounter=0 , mergedCounter=0;

    while(firstCounter < 10 && secondtCounter < 10){
        if(firstArray[firstCounter] < secondtArray[secondtCounter]){
            mergedArray[mergedCounter] = firstArray[firstCounter];
            firstCounter++;
        } else {
            mergedArray[mergedCounter] = secondtArray[secondtCounter];
            secondtCounter++;
        }
        mergedCounter++;
    }

    while(firstCounter < 10) {
        mergedArray[mergedCounter] = firstArray[firstCounter];
        firstCounter++;
        mergedCounter++;
    }

    while(secondtCounter < 10) {
        mergedArray[mergedCounter];
        secondtCounter++;
        mergedCounter++;
    }

    for(int j=0; j<20; j++){
        //cout << mergedArray[j] << endl;
    }
    cout << mergedArray[19];

    return 0;
}

在数组mergedArray[19] 的输出中,我得到如下信息:2686916!!!

我不知道为什么我会得到这个值。我该如何解决。以及为什么我得到这个值。

【问题讨论】:

  • This : mergedArray[mergedCounter]; 作为最终合并循环中的单个语句不会有太大作用。你忘记了作业部分。并注意您的编译器警告说“代码无效”会告诉您这一点。以高警告级别编译,弹出时不要忽略。
  • 您的编译器可能已经发出警告:语句无效 [-Wunused-value]

标签: c++ arrays sorting merge


【解决方案1】:

上次打错了。您可以提高警告级别,让编译器显示您的错字 (warning: statement has no effect [-Wunused-value])。

while(secondtCounter < 10) {
    mergedArray[mergedCounter];
    secondtCounter++;
    mergedCounter++;
}

应该是

while(secondtCounter < 10) {
    mergedArray[mergedCounter] = secondtArray[secondtCounter];
    secondtCounter++;
    mergedCounter++;
}

【讨论】:

  • 是的 .. TnX 这么多...我修好了。 :)
【解决方案2】:

正如 WhozCraig 的评论所指出的,您没有为 mergedArray[19] 分配任何值,因为您遗漏了语句的分配部分。

由于您尚未分配值,因此它会打印出之前使用时恰好位于该内存地址的任何值。如果你多次运行你的程序(就像它现在写的那样),你会看到那里的数字可能会改变。此外,如果您在分配任何内容之前打印出 mergeArray 中的值,您会看到更多这样无意义的(在当前应用程序中对您而言)数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-03
    • 2022-10-17
    • 1970-01-01
    • 2019-07-21
    • 2014-01-30
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多