问题:给定一个数组(ArrayInts)计算所有偶数整数和奇数整数的和,然后搜索数组中所有奇数整数之和的目标值使用二进制搜索。如果在数组中找到目标值,则显示找到目标值的数组索引,否则显示目标未找到。C++中的二进制搜索排序和索引
我没有得到正确答案。我不相信正在读取我想读取的数组。当我编译时,我得到数组是{6487456},偶数的总和是678,二叉搜索没有找到赔率549和目标。这是我现在的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double ArrayInts[]={54,152,99,-8,3,19,-11,260,27,-4,10,12,15,58,480,60};
int Bin_Search(double ArrayInts[],int low, int high, double target);
int main(void)
{
int i,j,n=16,sum_even,sum_odd, index,len;
double ArrayInts[16]={54,152,99,-8,3,19,-11,260,27,-4,10,12,15,58,480,60}, target;
//Implemeting Bubble sort
for(i=0;i<n-1;i++)
for(j=0;j<n-1;j++)
{
if (ArrayInts[j]>ArrayInts[j+1])
{
len=ArrayInts[j];
ArrayInts[j]=ArrayInts[j+1];
ArrayInts[j+1]=len;
}
}
//Function call to add even and odd numbers from array
for(i=0;i<16;i++)
{
if(i%2==0)
sum_even+=ArrayInts[i];
else
sum_odd+=ArrayInts[i];
}
printf("The array is {%d}\n",ArrayInts);
printf("The sum of all even numbers in the array is: %d\n",sum_even);
printf("The sum of all odd numbers in the array is: %d\n",sum_odd);
//Function call to search for target value
index = Bin_Search(ArrayInts,0,15,target);
if(index != -1)
printf("Target found at index %d\n", index);
else
printf("Target was not found\n");
system("pause");
return (0);
}
int Bin_Search(double ArrayInts[],int low, int high, double target)
{
int mid;
if (low>high)
return -1;
mid=(low+high)/2;
if(ArrayInts[mid]==target)
return(mid);
else if (ArrayInts[mid]<target)
return Bin_Search(ArrayInts, mid+1, high, target);
else
return Bin_Search(ArrayInts, low, mid-1, target);
}
你要我们来回答你贴有一个更好的C++实现的问题,或尝试修复你的代码?顺便说一下,这是一个使用C++算法的4或5行程序。 – PaulMcKenzie
你已经声明了同名的全局和局部变量,你的局部变量总是要在程序中读取。使用适当的命名约定。 –
我想要用目前正在完成的方式修复/向我解释代码。我从其他一些海报中看到代码应该是多么简短,但是,这超出了我正在学习的课程的范围,所以与我的教授不太一致 – mripkiss94