我正在编写一个简单的线性计算器。例如,用户可以输入两个方程(字符串),例如 y=5x+3 和 y=-3x+6。该计算器最基本的功能是它将返回这两条线的交点。
我似乎无法弄清楚的障碍是如何将字符串解析为两个数据:斜率和 y 截距。这是一个简单的计算器,因此两条线的格式均为 y=mx+b,但是,斜率和/或 y 截距都可能是非整数(即浮点数)。
我在字符串库中遇到了一个名为 stod 的函数,它将字符串中的数字转换为数值(我理解正确吗?)。
http://www.cplusplus.com/reference/string/stod/ http://www.cplusplus.com/reference/string/stod/
我的问题是,这个功能能完成这项工作吗?如果是这样,我到底如何使用“idx”参数?我不太明白。
如果这不起作用,我该如何解析用户输入的数据?
- 两个方程都是字符串 (y=mx+b)
- m 和 b 有专用于存储十进制值的私有变量(即 double m_ 和 double b_ 是私有成员变量)
这就是 idx 参数的工作原理:
#include <string>
#include <iostream>
int main(void)
{
std::string data = "y=5.9568x+3.14"; //say you have a string like this..
double y, x, m, b;
y = 0;
x = 0;
std::size_t offset = 0; //offset will be set to the length of characters of the "value" - 1.
m = std::stod(&data[2], &offset); //So we want to get the value "5.9568
b = std::stod(&data[offset + 3]); //When we reach this line, offset has a value of 6
std::cout<<b;
return 0;
}
那么现在您会问为什么它的值为 6?嗯,因为:
5.9568 正好是:6 个字符的长度。因此,当我们这样做时,在下一行
b = std::stod(&data[offset + 3]);
我们实际上给它提供了一个指向地址的指针x
+ 3..结果正好在开头3.14
.
换句话说,它相当于:
std::stod(&data[9]);
因此 idx 参数实际上是字符串中双精度字符的索引/长度。如果字符串是:
str = "3.14159"
Then std::stod(str, &idx)
将使 idx 等于:6。
如果字符串是:
str = "y = 1024.789"
then std::stod(&str[4], &idx)
将使 idx 等于: 8 从 &str[4] 开始..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)