问题描述
我有一个遍历数组的循环,试图找到哪个索引是字符串.它应该解决该值应该是多少.我不知道为什么,但是一旦if语句开始i
变为1,这给我的代码一个错误.我不太懂C ++.
I have a loop going through an array trying to find which index is a string. It should solve for what that value should be.I can't figure out why, but as soon as the if statements start i
becomes 1 which gives my code an error.I'm not very fluent in C++.
for(int i = 0; i < 4; i++) {
if(auto value = std::get_if<std::string>(&varArr[i])) {
solvedIndex = i;
auto value0 = std::get_if<float>(&varArr[0]);
auto value1 = std::get_if<float>(&varArr[1]);
auto value2 = std::get_if<float>(&varArr[2]);
auto value3 = std::get_if<float>(&varArr[3]);
//i changes to 1 when this if starts??
if(i = 0) {
solvedVar = (*value3 / *value1) * *value2;
} else if (i = 1) {
solvedVar = *value3 / (*value0 / *value2);
} else if (i = 2) {
solvedVar = *value0 / (*value3 / *value1);
} else {
solvedVar = *value1 * (*value0 / *value2);
}
break;
}
}
请注意,这些变量已在上面声明.另外,varArr
填充有值:
Note that these variables are declared above. Also, varArr
is filled with values:
std::variant<std::string, float> varArr[4];
int solvedIndex;
float solvedVar;
推荐答案
如前所述,在您的if
语句中,您正在使用赋值运算符(=
),但希望使用相等比较运算符(==
).对于变量i
,第一个if
语句将i
设置为等于0
,而if(0)
与if(false)
相同.因此,程序进入第一个else-如果将i
设置为1
并且if(1)
的值为true.然后,您的代码将完成else if (i = 1) {...}
中的块,然后结束.
As has been noted, in your if
statements, you are using the assignment operator (=
) but want the equality comparison operator (==
). For your variable i
the first if
statement sets i
equal to 0
and if(0)
is the same as if(false)
. So your program goes to the first else-if which sets i
equal to 1
and if(1)
evaluates to true. Your code then finishes the block within else if (i = 1) {...}
and then ends.
这篇关于C ++中变量本身的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!