我被要求编写一个程序,该程序从控制台获取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;
}
有人可以帮我吗?我仍然不担心该函数是否起作用,只是无法将这些值传递给我的函数。
答案 0 :(得分:1)
您需要包括标题<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
如果不是使用第二个参数nullptr
来指定有效的指针,则还可以检查字符串是否确实包含有效的数字。请参阅功能说明。
另一种方法是使用标头std::stod
中声明的标准字符串函数std::stoi
和<string>
,例如
double d = 0;
try
{
d = std::stod( argv[1] );
}
catch ( const std::invalid_argument & )
{
// .. some action
}