www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Average function using Variadic Functions method

reply pascal111 <judas.the.messiah.111 gmail.com> writes:
I'm programming average calculating function by using Variadic 
Functions method, but I didn't get yet what is the wrong in my 
code:

// D programming language

import std.stdio;
import core.vararg;
import std.conv;

float foo(...)
{

float x=0;

for(int i=0; i<_arguments.length; ++i){

x+=to!float(_arguments[i]);

}

x/=_arguments.length;

return x;

}

int main()
{


writeln(foo(2,3));

return 0;

}
Nov 02 2021
parent reply rikki cattermole <rikki cattermole.co.nz> writes:
You probably don't want to be using C variadics.

Instead try the typed one:

float mean(float[] input...) {
	// you don't want to divide by zero
	if (input.length == 0)
		return 0;

	float temp = 0;
	// floats and double initialize to NaN by default, not zero.
	
	foreach(value; input) {
		temp += value;
	}

	return temp / input.length;
}
Nov 02 2021
parent reply pascal111 <judas.the.messiah.111 gmail.com> writes:
On Tuesday, 2 November 2021 at 16:29:07 UTC, rikki cattermole 
wrote:
 You probably don't want to be using C variadics.

 Instead try the typed one:

 float mean(float[] input...) {
 	// you don't want to divide by zero
 	if (input.length == 0)
 		return 0;

 	float temp = 0;
 	// floats and double initialize to NaN by default, not zero.
 	
 	foreach(value; input) {
 		temp += value;
 	}

 	return temp / input.length;
 }
"input..." seems nice, where can I get more information about it?
Nov 02 2021
next sibling parent Mike Parker <aldacron gmail.com> writes:
On Tuesday, 2 November 2021 at 16:35:40 UTC, pascal111 wrote:

 "input..." seems nice, where can I get more information about 
 it?
"Typesafe variadic functions" https://dlang.org/spec/function.html#typesafe_variadic_functions
Nov 02 2021
prev sibling parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 11/2/21 9:35 AM, pascal111 wrote:

 "input..." seems nice, where can I get more information about it?
I include most of the language in this free book: http://ddili.org/ders/d.en/index.html which has an Index Section that I find useful to locate information: http://ddili.org/ders/d.en/ix.html I searched for '...' in that page and was happy that one of the candidates was "..., function parameter" which took me here: <http://ddili.org/ders/d.en/parameter_flexibility.html#ix_parameter_flexibility....,%20function%20parameter> Note: I've heard before that the links are broken but it works for me. (I enclosed the link with <> to help with it.) Ali
Nov 02 2021