[英]how to save the conditional statement of an if command as a string?
I have a numerical algorithm.我有一个数值算法。 I create a set of x, and y coordinates for points in R^2.
我为 R^2 中的点创建了一组 x 和 y 坐标。 Then, I use a rule to see which points are suitable for my purpose, a simple if statement like below:
然后,我使用一个规则来查看哪些点适合我的目的,一个简单的 if 语句如下所示:
int N = 0;
for (int i1 = -xN; i1 < xN + 1; i1++)
{
for (int i2 = -yN; i2 < yN + 1; i2++)
{
double x = dist(0) * i1;
double y = dist(1) *i2;
if (sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91)
{
Points.row(N) = trans(vec{ x, y});
N = N + 1;
}
}
}
Since I change the rule (that is, sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91) in each example, I was wondering if I could store it as a string variable and then save it with other parameters of the example in a single text file.由于我在每个示例中更改了规则(即 sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91),我想知道是否我可以将其存储为字符串变量,然后将其与示例的其他参数一起保存在单个文本文件中。 something like this:
像这样的东西:
ofstream myfile;
myfile.open("resultEXAMPLE2D01.txt");
myfile << "xN = [" << xN << "];" << endl;
myfile << "N = [" << output.N << "];" << endl;
myfile << "% Condition is " << cond << endl;
myfile.close();
where "cond" should be "sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91" in this case.在这种情况下,“cond”应该是“sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91”。 So, in "cond" x and y are not variables, I just look at the whole thing as a text/string.
因此,在“cond”中,x 和 y 不是变量,我只是将整个事物视为文本/字符串。 but then inside the if statement I want to evaluate some criteria for x and y, so this "cond" should be a function with two doubles as input and a bool as output.
但是在 if 语句中,我想评估 x 和 y 的一些标准,所以这个“条件”应该是一个 function,两个双精度值作为输入,一个布尔值作为 output。 Is there some straight forward way to have this kind of type conversion?
有没有一些直接的方法来进行这种类型转换?
Looks like you need Stringification
.看起来你需要
Stringification
。 You can read more about it here:你可以在这里读更多关于它的内容:
So, you can define macros and pass to it your condition.因此,您可以定义宏并将您的条件传递给它。 Inside macros you can put your computation code, use passed condition and also stringify your condition (place
#cond
for cond
paramater) for output to somewhere (file, console, ...).在宏内部,您可以将计算代码、使用传递的条件以及将 output 的条件(放置
#cond
用于cond
参数)字符串化到某处(文件、控制台等)。
Here is example:这是示例:
int N = 0;
#define Calculate(cond) \
{ \
N = 0; \
for (int i1 = -xN; i1 < xN + 1; i1++) \
{ \
for (int i2 = -yN; i2 < yN + 1; i2++) \
{ \
double x = dist(0) * i1; \
double y = dist(1) *i2; \
\
if (cond) \
{ \
Points.row(N) = trans(vec{x, y}); \
N = N + 1; \
} \
\
} \
} \
\
std::cout << "Condition: " << #cond << std::endl; \
}
int main()
{
Calculate(sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91)
Calculate(x > 0)
return 0;
}
Program output:程序 output:
Condition: sqrt(pow(x, 2) + pow(y, 2)) > 0.8 && abs(x) < 3.1 && abs(y) < 3.91
Condition: x > 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.