C ++中变量本身的变化 [英] Variable changes on it's own in C++

查看:85
本文介绍了C ++中变量本身的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遍历数组的循环,试图找到哪个索引是字符串.它应该解决该值应该是多少. 我不知道为什么,但是一旦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 ++中变量本身的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆