[英]C++ Find biggest element in an array with negative values
我将变量biggest
设置为 0,然后循环数组中的每个元素并检查它是否大于当前biggest
,它适用于常规数字,但不适用于负数。
我怎样才能修复它以使用底片呢?
#include <iostream>
using namespace std;
int main(){
int a[7] = { -1, -3, -4, -5, -6, -1, -7 }; //array
int biggest = 0; //biggest number in the array
for(int i = 0; i < 4; i++) { //looping every element in the array
if(a[i] > biggest) { //checking if the current number is bigger then the biiger number
biggest = a[i]; //setting the biggest number to be = to the current number
}
}
cout << biggest << endl; //printing the biggest number
}
您可以将初始biggest
作为数组的第一个元素。 您不需要使用任何限制。
#include <iostream>
using namespace std;
int main() {
int a[7] = { -1, -3, -4, -5, -6, -1, -7 };
int biggest = a[0];
for (int i = 1; i < 7; i++){
if (a[i] > biggest){
biggest = a[i];
}
}
cout << biggest << endl;
}
使用INT_MIN
因为它在int
中具有最小值,您可以通过在程序中添加#include<climits>
库来使用它
它会打印零,但如果你想从你的数组中获取最大的数字
初始化你的int biggest = INT_MIN;
而不是int biggest = 0;
INT_MIN
的值是-2147483647 - 1
这将解决您的问题。
还包括#include <bits/stdc++.h>
用于INT_MIN
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.