简体   繁体   English

即使 if 为真,为什么 if 语句始终是 else 部分?

[英]Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.最后的 if 语句有问题。 **if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". **如果用户输入的数字的幼崽总和等于数字本身,请说“....”。 Else, say "....." **否则,说“.....”**

The problem is that it always jumps the if part to the else.问题是它总是将 if 部分跳转到 else 。

Its a task from the uni, no homework or nothing, just training.这是大学的任务,没有功课或什么都没有,只是训练。 IF you have suggestions on how to better I would appreciate that too.如果您有关于如何改进的建议,我也将不胜感激。

Thank you!谢谢!

{
    int n;  

    cout << "Write a number different from 0 -> ";
    cin >> n;
    
    while (n == 0) 
    {
        cout << "Choose another number -> ";
        cin >> n;
    }

    cout << "Good number " << n << " is!" << "\n";
    cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
    Sleep(1000);
    
    vector<int> vecN;

    while (n != 0)
    {
        int digit = n % 10;
        n /= 10;
        cout << n << endl;
        cout << "Digit: " << digit << endl;
        vecN.push_back(digit);
        Sleep(750);
    }
    cout << "There you go!" << endl;
    Sleep(1000);
    cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
    Sleep(2500);
    
    vector<int> sums;

    for (auto i = vecN.begin(); i != vecN.end(); i++)
    {
        Sleep(500);
        int Cubes = pow(*i, 3);
        
        cout << Cubes << endl;
        sums.push_back(Cubes);
    }

    Sleep(1300);
    cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
    Sleep(3000);

    int armSum = accumulate(sums.begin(), sums.end(), 0);

    if ( armSum == n )
    {
        cout << "Sum: " << armSum << endl;
        Sleep(500);
        cout << "That's an Armstrong Number!" << "\n"
            "The sum of the cubs of each digit in the number is equal to that same number!" << endl;
    }
    else
    {
        cout << "Sum: " << armSum << endl;
        Sleep(500);
        cout << "That's not an Armstrong Number!" << endl;
    }
        
    return 0;
} ```

When the if -part is entered, the else -part won't be entered any more.当输入if -part 时, else -part 将不再被输入。 Note that your if/else is not surrounded by a loop.请注意,您的if/else没有被循环包围。 So when control passes by once, eg when having entered n==0 , then it has passed by and won't step into neither the if nor the else -part a second time.所以当控制通过一次时,例如当进入n==0 ,那么它已经通过并且不会第二次进入ifelse部分。

Try something like尝试类似的东西

while (n==0) {
    cout << "Choose another number -> ";
    cin >> n;
}

// continue here; n is != 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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