【问题标题】:How do I pass main args to some other function?如何将主要参数传递给其他函数?
【发布时间】:2020-06-27 14:38:10
【问题描述】:

我被要求编写一个程序,该程序从控制台获取 3 个参数,然后使用这些值来估计其他函数的值。我真的不知道如何在其他函数中使用这些值。我试图做这样的事情,但它不起作用:

#include <iostream>

using namespace std;

void logis(double a, double xz, int n){
    if (n == 0){return;}
    else{
        double x = a*xz(1-xz);
        logis(a, x, n-1);
        cout << n << "  " << x << endl;
    }
}

int main(int argc, char* argv[]){

    if (argc != 4){
        cout << "You provided 2 arguments, whereas you need to provide 3. Please provide a valid number of parameteres";
    }
    else{
        double a = argv[1];
        double x0 = argv[2];
        int n = argv[3];
        logis(a, x0, n);
    }

return 0;
}

谁能帮我解决这个问题?我还不关心函数是否有效,我只是无法将这些值传递给我的函数。

【问题讨论】:

  • argv[n] 是字符串,您必须先以某种方式将它们转换为所需的类型。例如,您可以使用它来将参数转换为双精度:sscanf(argv[2], "%lf", &amp;x0);
  • 使用 atof() 转换为浮点数

标签: c++ function command-line-arguments main args


【解决方案1】:

您需要包含标题&lt;cstdlib&gt;

#include <cstdlib>

并使用函数strtodstrtol(或atoi)。例如

    double a = std::strtod( argv[1], nullptr );
    double x0 = std::strtod( argv[2], nullptr );
    int n = std::atoi( argv[3] );

这是一个演示程序

#include <iostream>
#include <cstdlib>

int main() 
{
    const char *s1 = "123.45";
    const char *s2 = "100";

    double d = std::strtod( s1, nullptr );
    int x = std::atoi( s2 );
    std::cout << "d = " << d << ", x = " << x << '\n';

    return 0;
}

它的输出是

d = 123.45, x = 100

如果不是第二个参数等于nullptr 来指定有效指针,那么您还可以检查字符串是否确实包含有效数字。见功能说明。

另一种方法是使用在标头&lt;string&gt; 中声明的标准字符串函数std::stodstd::stoi,例如

double d = 0;

try
{
    d = std::stod( argv[1] );
}
catch ( const std::invalid_argument & )
{
    // .. some action
}

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多