[英]C program to output the largest element of array with the index of the largest element of array
[英]How to display the index of the largest value of array in C?
用戶必須輸入 10 個值,並且您應該顯示最大值及其索引。 我已經使用 for 循環獲得了最大值。
largest = num[0];
for (n = 1; n < 10; n++) {
if (largest < num[n])
largest = num[n];
}
但我不知道如何獲得它的索引。 我試過用谷歌搜索它,但它們是在 Java 中的(PS 我只是一個初學者)
不存儲最大值,只存儲索引:
size_t index_of_max = 0;
for(size_t n = 1; n < 10; n++) {
if(numbers[index_of_max] < numbers[n]) {
index_of_max = n;
}
}
另外,只是一個小的文體注釋:始終為if
使用大括號,即使它們是一個語句。 這是可以避免錯誤的好習慣(不這樣做會導致許多安全問題)。
總是索引從 0 開始。試試這個我希望這可以幫助你。
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.