1

I have to find the average of double numbers that the user inputs at the command line, so my program should work with any amount of inputs. I understand that I have to find the sum of all of the numbers and then divide by the number of inputs.

I was thinking, to find the number of inputs, I would use sscanf to read "char *num" in my argument list. Because sscanf returns the characters read. And then I was thinking of using that to divide the sum by to get the average. But I'm having trouble with my code. :(

#include <stdio.h>

void average(int arg_list, char *num[])
{
   int x;
   double sum, average;

   x = sscanf(num, "%s\n", &x);

   for (int i = 0; i != '\0'; i++)
   {
      sum = sum + num[i];
   }

   average = sum/x;
   printf("%lf\n", average);;
}

int main(int argc, char *argv[])
{
   if (argc == 0)
   {
      perror("Error!\n");
   }

   average(argc, argv);
}

Specifically, when I try to compile my program, the compiler complains about the "sscanf" and the sum. :/

4

2 回答 2

2

"%s"读取一个字符串。你想从字符串中读取一个双精度,所以你应该使用"%lf". 循环内:

double sum = 0; //you forgot to initialize
//start from i=1, not 0; the first argument is the program's name
for (int i = 1; i < arg_list; i++) {
    double x;
//from the i'th argument, read a double, into x :
    sscanf(num[i], "%lf", &x);
    sum += x;
}
average = sum/(arg_list-1);

您还应该修复您的支票:

if (argc <= 1) {
   perror("Error!\n");
}
于 2013-05-28T22:22:17.703 回答
0
#include <stdio.h>
#include <stdlib.h>

void average(int arg_list, char *num[])
{
   double sum = 0, average;//sum : 0 initialize
   int i;
   for (i = 1; i < arg_list; i++){
      sum = sum + atof(num[i]);
   }
   average = sum/(--i);
   printf("%lf\n", average);;
}

int main(int argc, char *argv[])
{
   if (argc < 2)//include program name argv[0], argc == 1 even when only ./a.out
   {
      perror("Error!\n");
      return -1;
   }

   average(argc, argv);

    return 0;
}
于 2013-05-28T22:35:28.767 回答