300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > @requestbody 接受int参数_C++之指针作为函数参数

@requestbody 接受int参数_C++之指针作为函数参数

时间:2024-02-27 14:04:08

相关推荐

@requestbody 接受int参数_C++之指针作为函数参数

C++ 允许您传递指针给函数,只需要简单地声明函数参数为指针类型即可。

下面的实例中,我们传递一个无符号的 long 型指针给函数,并在函数内改变这个值:

#include <iostream>#include <ctime>using namespace std;void getSeconds(unsigned long *par);int main (){unsigned long sec;getSeconds( &sec );// 输出实际值cout << "Number of seconds :" << sec << endl;return 0;}void getSeconds(unsigned long *par){// 获取当前的秒数*par = time( NULL );return;}

编译以上程序得到结果:

Number of seconds :1604050210

能接受指针作为参数的函数,当然也能接受数组作为参数,如下所示:

#include <iostream>#include <ctime>using namespace std;double getAverage(int *arr, int size);int main() {// unsigned long sec;int arr[5] = {1, 3, 5, 1, 0};double avg;avg = getAverage(arr, 5);cout << "average is: " << avg << endl;return 0;}double getAverage(int *arr, int size){int i, sum=0;double avg;for(i = 0; i < size; i++){sum += arr[i];}avg = double(sum) / size;return avg;}

编译并执行以上程序,输出结果:

average is: 2

以上是C++模板的示例,如有疑问或建议请评论。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。