简体   繁体   中英

c# newbie: if statement && with int

i'm crossing a problem in the code i made for the second Euler problem (sum of the even fibonacciresults until 4million.

i'm using an if statement with integers (also tried long, ...) and it sais the '&&' can not be used with int. how can i fix this or did i make another mistake ?

tnx in advance

        int result = 3;
        int resultMinEen = 1;
        int resultMinTwee = 2;        

        for (int i = 1; i <= 4000000; i++)
        {
            if ((i % 2) == 0 && i = resultMinEen + resultMinTwee)
            {
                result += i;
                resultMinTwee = resultMinEen;
                resultMinEen = result;
            }
        }

(i = resultMinEen + resultMinTwee) is what is going to return an integer. It is setting the value of i, which is the loop variable. If this is what you are intending to do then it is very bad practice and you should set a second, temporary variable inside the body of the if test and use that. If you are attempting to test that i is equal to resultMinEen + resultMinTwee, then make it == (comparison operator) instead of = (assignment operator).

there is difference between = and == :)

 int result = 3;
    int resultMinEen = 1;
    int resultMinTwee = 2;



    for (int i = 1; i <= 4000000; i++)
    {
        if (((i % 2) == 0) && (i == resultMinEen + resultMinTwee))
        {
            result += i;
            resultMinTwee = resultMinEen;
            resultMinEen = result;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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