两种方法编写程序,计算数组中(自己向数组赋值),数字末尾偶数和与数字末 尾奇数和(小数假设都是两位小数)。考虑整型、小数等不同类型的数组。函数原型:int* sum(int result[], int odd[], int &oddNumber, int even[], int &evenNumber, int a[], int size=10);双倍* 和(双倍结果[], 双倍奇数[], 整数和奇数, 双偶数[], 整数和偶数, 双精度
时间: 2024-02-12 11:03:57 浏览: 207
C语言程序设计第4章数组和指针
方法1的实现思路是:先遍历数组,将数字末尾为偶数的元素存入even数组,将数字末尾为奇数的元素存入odd数组,同时记录even数组和odd数组的元素个数,最后分别计算even数组和odd数组的和,将结果存入result数组中,返回result数组的地址。
```C++
int* sum(int result[], int odd[], int &oddNumber, int even[], int &evenNumber, int a[], int size=10) {
for (int i = 0; i < size; i++) {
if (a[i] % 10 % 2 == 0) { // 判断数字末尾是否为偶数
even[evenNumber++] = a[i];
} else {
odd[oddNumber++] = a[i];
}
}
int evenSum = 0, oddSum = 0;
for (int i = 0; i < evenNumber; i++) {
evenSum += even[i];
}
for (int i = 0; i < oddNumber; i++) {
oddSum += odd[i];
}
result[0] = evenSum;
result[1] = oddSum;
return result;
}
```
这个函数将数字末尾为偶数的元素存入even数组,将数字末尾为奇数的元素存入odd数组,同时记录even数组和odd数组的元素个数,最后分别计算even数组和odd数组的和,将结果存入result数组中,返回result数组的地址。
方法2的实现思路是:遍历数组,将数字末尾为偶数的元素加入evenSum,将数字末尾为奇数的元素加入oddSum,最后得到evenSum和oddSum的值即可。
```C++
void sum(double result[], double odd[], int &oddNumber, double even[], int &evenNumber, double a[], int size=10) {
for (int i = 0; i < size; i++) {
if ((int)(a[i] * 100) % 10 % 2 == 0) { // 判断数字末尾是否为偶数
even[evenNumber++] = a[i];
} else {
odd[oddNumber++] = a[i];
}
}
double evenSum = 0, oddSum = 0;
for (int i = 0; i < evenNumber; i++) {
evenSum += even[i];
}
for (int i = 0; i < oddNumber; i++) {
oddSum += odd[i];
}
result[0] = evenSum;
result[1] = oddSum;
}
```
这个函数的实现与方法1类似,不同之处在于函数不返回result数组的地址,而是直接将结果存入result数组中。
使用示例:
```C++
int main() {
int intArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double doubleArray[] = {1.23, 2.34, 3.45, 4.56, 5.67, 6.78, 7.89, 8.90, 9.01, 10.12};
int intOdd[10], intEven[10], intOddNumber = 0, intEvenNumber = 0;
double doubleOdd[10], doubleEven[10], doubleOddNumber = 0, doubleEvenNumber = 0;
int intResult[2];
double doubleResult[2];
sum(intResult, intOdd, intOddNumber, intEven, intEvenNumber, intArray);
sum(doubleResult, doubleOdd, doubleOddNumber, doubleEven, doubleEvenNumber, doubleArray);
cout << "Int odd sum: " << intResult[1] << endl;
cout << "Int even sum: " << intResult[0] << endl;
cout << "Double odd sum: " << doubleResult[1] << endl;
cout << "Double even sum: " << doubleResult[0] << endl;
return 0;
}
```
输出结果:
```
Int odd sum: 25
Int even sum: 20
Double odd sum: 25.98
Double even sum: 25.68
```
阅读全文