简体   繁体   English

编写一个程序,该程序读取所有命令行参数并打印平均值,c ++

[英]Write a program that reads in all the command line arguments and prints the average, c++

//review3
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;

double average;
int main(int argc, char* argv[])
{
    int num1 = atoi (argv[1]);
    int num2 = atoi (argv[2]);
    int num3 = atoi (argv[3]);
    average = ((num1 + num2 + num3) / 3);
    cout << average << endl;
}

I am not sure how to tackle this problem if I need to calculate the average of all of the command line arguments? 如果我需要计算所有命令行参数的平均值,我不确定如何解决该问题? This is how I would do it with 3 CLA's but I am unsure how I would do it without knowing a set amount of CLA's for this problem. 这就是我要使用3个CLA的方式,但是我不确定在不知道此问题的CLA设置量的情况下该如何做。 Does anyone also know how to do this if you had to find the median? 如果您必须找到中位数,还有谁知道该怎么做?

Below is the simple program. 下面是简单的程序。

int sum = 0 ;
for ( int i = 1; i < argc; i++ )
{
  sum = sum + atoi(argv[i]) ;  //Exclusion of argv[0] is no incidence...
}

Then you can do whatever you want to do with sum 然后,您可以使用sum做任何您想做的事

In the declaration of main int argc is the number of arguments given. 在main int argc的声明中, int argc是给定的参数数量。 You can use a for loop to iterate through your arguments and calculate the average: 您可以使用for循环遍历您的参数并计算平均值:

// Your includes here
// ...

int main(int argc, char* argv[])
{
    int average = 0;

    for(int i = 1; i < argc; i++) // argv[0] is the name of your program, so we are skipping it
    {
        average += atoi(argv[i]);
    }

    average = average / (argc - 1);
}

argc will give you the number of arguments given to main(). argc将为您提供给main()的参数数量。

Note that argc will be ONE, not zero if you provide no argument as argv[0] is the file name of the executable. 请注意,如果您不提供任何参数,则argc将为ONE,而不是零,因为argv [0]是可执行文件的文件名。

To get the median, the following should do the trick: 要获得中位数,应使用以下技巧:

float median;

// Get a sorted list of the integers
std:list<int> args;
for(int i = 1; i < argc; i++)
{
    args.push_back(atoi(argv[i]));
}
args.sort();

// Extract median from the sorted array of integers
int middle_index = args.size() / 2;
if (args.size() % 2 == 1)
{
    // For odd number of values, median is middle value
    median = args[middle_index];
}
else
{
    // For even number of values, median is average of the two middle values
    median = (args[middle_index-1] + args[middle_index]) / 2.0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM