Reputation: 13
I have this homework to do: "Determine the minimum of 10 precision double numbers from a string (implicit values or from the KB) using a function with a variable number of parameters. The first 7 values will be considered initially, next the last 3 and at the end these 2 values." Well I made it all but I don't know why it gives me some strange results. Here's the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <conio.h>
double min(double,...);
void main(){
double a,b,c;
printf("Introduceti numerele: ");
scanf("%lf%lf%lf",&a,&b,&c);
printf("\nMinimul este %lf",min(10,1.34,4.34,7,5.23,6.23,2,8.232,a,b,c));
_getch();
}
double min(double x,...){
int i;
double y;
va_list ap;
va_start(ap,x);
y=va_arg(ap,double);
for(i=0;i<x;i++){
if(y>va_arg(ap,double))
y=va_arg(ap,double);
}
va_end(ap);
return y;
}
Also i don't know why the compiler knows about what argument is next cause i is not used in va_arg(ap,double).
for(i=0;i<x;i++){
if(y>va_arg(ap,double))
y=va_arg(ap,double);
Upvotes: 1
Views: 100
Reputation: 210877
The first parameter in the call to your function min
is the number of arguments, and it has the type int
:
#include <stdarg.h>
double min( int numberOfArgs, ... )
// ^^^
{
va_list argptr;
va_start( argptr, numberOfArgs ); // initialize argument pointer
double minData = va_arg( argptr, double ); // initialize the minimum with the first argument
// and increment argument pointer
for ( int i = 1; i < numberOfArgs; i ++ ) // for all of the following arguments
{
double data = va_arg( argptr, double ); // get argument and increment argument pointer
if ( data < minData ) // test if argument is less than mnimum
minData = data;
}
va_end( argptr );
return minData;
}
Ensure that all of your arguments in the argument list are floating point values of type double
:
int main()
{
double a, b, c;
printf("Introduceti numerele: ");
scanf_s("%lf%lf%lf", &a, &b, &c);
double minVal = min( 10, 1.34, 4.34, 7.0, 5.23, 6.23, 2.0, 8.232, a, b, c)
// ^^ ^^
printf("\nMinimul este %lf", minVal);
return 0;
}
Upvotes: 3