如何将主要参数传递给其他函数?
How do I pass main args to some other function?
我被要求编写一个程序,从控制台获取 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;
}
有人可以帮我吗?我还不关心函数是否有效,我只是无法将这些值传递给我的函数。
您需要包含 header <cstdlib>
#include <cstdlib>
并使用函数 strtod
和 strtol
(或 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
if 而不是第二个参数等于 nullptr
来指定一个有效的指针,那么您还可以检查该字符串是否确实包含一个有效的数字。见函数说明
另一种方法是使用在 header <string>
中声明的标准字符串函数 std::stod
和 std::stoi
,例如
double d = 0;
try
{
d = std::stod( argv[1] );
}
catch ( const std::invalid_argument & )
{
// .. some action
}
我被要求编写一个程序,从控制台获取 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;
}
有人可以帮我吗?我还不关心函数是否有效,我只是无法将这些值传递给我的函数。
您需要包含 header <cstdlib>
#include <cstdlib>
并使用函数 strtod
和 strtol
(或 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
if 而不是第二个参数等于 nullptr
来指定一个有效的指针,那么您还可以检查该字符串是否确实包含一个有效的数字。见函数说明
另一种方法是使用在 header <string>
中声明的标准字符串函数 std::stod
和 std::stoi
,例如
double d = 0;
try
{
d = std::stod( argv[1] );
}
catch ( const std::invalid_argument & )
{
// .. some action
}