#include <iostream>
const int ArSize = 12;
void sum_and_sub(int arr1[], int arr2[], int ArSize, int sum_result[], int sub_result[]);
int main()
{using namespace std;int arr1[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };int arr2[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };int sum_result[ArSize], sub_result[ArSize];sum_and_sub(arr1, arr2, ArSize, sum_result, sub_result);for (int i = 0; i < ArSize; i++){cout << sum_result[i] << " ";};cout << endl;for (int i = 0; i < ArSize; i++){cout << sub_result[i] << " ";};cout << endl;return 0;
}
void sum_and_sub(int arr1[], int arr2[], int ArSize, int sum_result[], int sub_result[])
{for (int i = 0; i < ArSize; i++){sum_result[i] = arr1[i] + arr2[i];sub_result[i] = arr1[i] - arr2[i];};
}
這種寫法的問題很明顯:
首先是寫法復雜,因為要預先聲明多個輸入多個輸出;
其次是因為你需要的輸入和輸出都是作為函數的輸入,所以容易混淆;
最后在某些情況下會導致未初始化的值。
#include <iostream>
const int ArSize = 12;struct Result {int sum_result[ArSize];int sub_result[ArSize];Result(){memset(this, 0, sizeof(Result));}
};Result sum_and_sub(int arr1[], int arr2[], int ArSize);using namespace std;int main()
{int arr1[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };int arr2[ArSize] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };Result results = sum_and_sub(arr1, arr2, ArSize);for (int i = 0; i < ArSize; i++){cout << results.sum_result[i] << " ";};cout << endl;for (int i = 0; i < ArSize; i++){cout << results.sub_result[i] << " ";};cout << endl;return 0;
}Result sum_and_sub(int arr1[], int arr2[], int ArSize)
{Result results;for (int i = 0; i < ArSize; i++){//cout << results.sum_result[i];results.sum_result[i] = arr1[i] + arr2[i];results.sub_result[i] = arr1[i] - arr2[i];};return results;
}
return可以返回數組嗎。這種寫法相對來說比上面顯得整潔,結構化也比較好管理。
后續還有用指針的寫法。
REF:https://blog.csdn.net/shi2xian2wei2/article/details/95488707
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态