我是一个初学者 c 程序员。我试图制作一个程序,它将返回一个数组的最高值。为此,你应该首先对数组进行排序。而对于排序数组我使用了冒泡排序方法,并且在做了冒泡排序之后我的计划是返回排序数组的第一个元素。这样它将返回数组的最高值。但是我运行代码的那一刻它正在打印垃圾值。这里是代码。
#include <stdio.h>
int bub(int arr[]);
int main(){
//creating an array
int arr[] = {23,4,65,76,87};
/*calling the function. Here I am printing it. because when I just call the function it is not
returning anything*/
int abs = bub(arr);
printf("%d",abs);
}
// defining function
int bub(int arr[]){
// creating a loop to go till the end of the array
for (int i = 0 , len = sizeof(arr[i]) / sizeof(int) ; i<len ; i++){
for (int j = 0;j<i;j++){
// swaping if the the value is greater than the next value of the array
if (arr[j]>arr[j+1]){
// swaping the values
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
// printing the first value to get the highest value
printf("%d",arr[0]);
}
}
}
}
为什么它返回打印垃圾值?有没有更好的方法来找到一个数组的最高值?。或者有什么我可以在这个代码中改进?
请回复。
请注意,您正在使用 '& gt;' 在这种情况下比较第一个元素将是最低的,我改变了它,最好在 main 函数中声明数组的大小,并将其传递给函数作为您想要使用它的参数。
#include <stdio.h>
int bub(int arr[], int n);
int main(){
//creating an array
int arr[] = {23,4,65,76,87};
int n = sizeof(arr) / sizeof(int);
int abs = bub(arr, n);
printf("\n%d",abs);
}
// defining function
int bub(int arr[], int n){
// creating a loop to go till the end of the array
for (int i = 0; i<n-1 ; i++){
for (int j = 0;j<n-i-1;j++){
// swaping if the the value is greater than the next value of the array
if (arr[j] < arr[j+1]){
// swaping the values
// int t = arr[j]; arr[j]=arr[j+1]; arr[j+1]=t;
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
// printing the first value to get the highest value
//printf("%d",arr[0]);
}
}
}
return arr[0];
}
另一种更简单的方法是遍历数组一次,以找到最高或最低值。像这样
int highest = arr[0];
for (int i = 1; i<n ; i++){
if(arr[i] > highest) highest = arr[i];
}
printf("%d", highest);
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(68条)