简体   繁体   English

运行期间通过参数传递的平方根

[英]Square root from parameter passing during the run

I'm newbie in C/C++ languages and I want to ask one simple question. 我是C/C++语言的新手,我想问一个简单的问题。 I've written the following code: 我编写了以下代码:

#include <stdio.h>
#include <math.h>

int main(int argc, char ** argv){
    printf("Square root from %f is %f", argv[1], sqrt(argv[1]));
}

But it doesn't work because argv[1] has type char* . 但这不起作用,因为argv [1]的类型为char* How can I cast argv[1] to double and if it's impossible throw an exception? 如何将argv[1]为两倍,如果不可能则抛出异常?

The easiest solution is to use atof . 最简单的解决方案是使用atof Therefore, you would be writing something like this: 因此,您将编写如下内容:

printf("Square root from %s is %f", argv[1], sqrt(atof(argv[1])));

Of course, you could look into higher-level alternatives like C++11's std::stod , but it would be an overkill for this simple case, but if you insist on using C++ code later, I would write this if I were you: 当然,您可以研究诸如C ++ 11的std :: stod之类的更高级别的替代方法,但是对于这种简单情况而言,这是一个过大的选择,但是如果您以后坚持使用C ++代码,那么如果您是我,我会写这个代码:

std::string myString = argv[1];
std::cout << "Square root from " << argv[1] << " is "
          << std::sqrt(std::stod(myString)) << std::endl;

You would also need to change the first placeholder to %s because you are printing the first argument in there, which is as you wrote a string. 您还需要将第一个占位符更改为%s因为您要在其中打印第一个参数,即编写字符串时。

In your final code, please also make sure that argc is at least 2 before trying to access the second item of the string array. 在您的最终代码中,在尝试访问字符串数组的第二项之前,还请确保argc至少为2。

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

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