变量参数C ++ [英] variable arguments C++
本文介绍了变量参数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力学习C ++;问题来自可变参数,程序编写如下: -
I m trying to learn C++; the problem comes with variable arguments the program is written as below:-
#include<iostream>
#include"stdarg.h"
using namespace std;
int sum(int count,...)
{
if(count<=0)
return 0;
va_list arg_ptr;
va_start(arg_ptr,count);
int s=0;
for(int i=0;i<count;i++)
s+=va_arg(arg_ptr,int);
va_end(arg_ptr);
return s;
}
int main()
{
cout << sum(2,4,6) << endl;// runs fime as cout << sum(2,4) output is 6 fine but cout << sum(2,4,6) gives output 10
//which i suppose must be 12
cin.get();
cin.ignore();
}
推荐答案
总和(2,4,6)的输出
应该是10而不是12 ...你的第一个参数是其余参数的计数器。如果您希望答案为12,则应致电sum(3,2,4,6)
The output fromsum(2,4,6)
should be 10 not 12 ... your first parameter is a counter for the rest of the parameters. If you want the answer to be 12 you should callsum(3,2,4,6)
您好。
对于总和(2,4,6),10是正确的结果。
对于总和(2,4),6是错误的。 />
sum函数的第一个参数(count)告诉我们将跟随多少个数字,所以...
sum(2,4,6) )告诉总和2个数字,哪个值是4和6,总共10个。
sum(2,4)告诉sum2数字,但第二个没有提供,所以它将被读取从错误的内存位置(可能来自存储第一个参数,当前为2的堆栈位置)。
sum(2,4)应该用sum替换(1,4)。
问候,
Daniele。
Hi.
For sum(2,4,6), 10 is correct result.
For sum(2,4), 6 is wrong.
The first argument (count) of the sum function tells how many numbers will follow, so ...
sum(2,4,6) tells to sum 2 numbers which values are 4 and 6, for a total of 10.
sum(2,4) tells to sum2 numbers, but the second is not provided, so it will be read from a wrong memory location (probably from the stack location where the first argument, currently 2, is stored).
sum(2,4) should be replaced with sum(1,4).
Regards,
Daniele.
这篇关于变量参数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文