更新:我在int main()的末尾遇到一个关于数据堆栈被破坏的错误.谢谢.我的代码如下:
#include <iostream>#include <conio.h>using namespace std;int indexofSmallestElement(double array[],int size);int main(){ int size = 10; double array[10];for (int i = 0; i <= size; i++){ cout << "Enter an integer: " << endl; cin >> array[i];}indexofSmallestElement(array,size);}int indexofSmallestElement(double array[],int size){int index = 0;if (size != 1){ int n = array[0]; for (int i = 1; i < size; i++) { if (array[i] < n) { n = array[i]; index = i; } }}return index;}解决方法 很多人向您展示了indexofSmallestElement的变体.我将包括我的解释为什么我认为它更好:
int indexofSmallestElement(double array[],int size){ int index = 0; for(int i = 1; i < size; i++) { if(array[i] < array[index]) index = i; } return index;}
你会注意到我取消了你用来保存到目前为止遇到的最小值的n变量.我这样做是因为,根据我的经验,必须保持两个不同的事物同步可能是微妙的错误的来源.即使在这个简单的情况下,它也是多个错误的根源,其中最重要的是你的n被声明为int但你在其中分配了double类型的值.
底线:取消n变量,只记录一件事:索引.
总结以上是内存溢出为你收集整理的c – 返回数组中最小元素的索引全部内容,希望文章能够帮你解决c – 返回数组中最小元素的索引所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)