【发布时间】: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]