计算9个小球中哪个比较重
#include<iostream>
using namespace std;
int CompareWeight(int *arr, int num)
{
int result,t;
int i1, i2, i3;
int a;//计算因子
i1 = i2 = i3 = 0;
t = num / 3;
for (int i = 0; i <t; i++)
{
i1 += arr[i];
i2 += arr[i + t];
i3 += arr[i + t * 2];
}
//先比较两组球
if (i1 > i2)
a = 0;
if (i1 < i2)
a = 1;
if (i1 == i2)
a = 2;
int *narr = new int[t];//开辟一段空间,记录比较重的一组球-用的是new动态内存
if (t == 1)
result = a;//here have a question
else
{
for (int j = 0; j < t; ++j)
{
narr[j] = arr[j + a*t];//记录重的那组球
}
result = CompareWeight(narr, t) + t*a;
}
delete[] narr;
return result;
}
int main()
{
int Ball[] = { 1, 1, 9, 1, 1, 1, 1, 1, 1 };
int maxBall = CompareWeight(Ball, 9);
cout << "这个重的球是:" << maxBall << endl;
system("pause");
return 0;
}