簡體   English   中英

即使不滿足條件,“ if”語句也會運行

[英]“if” statement runs even though the conditions aren't met

如下所示,如果僅int outcome為7或11,則int result應該分配為1。但是,即使在模擬中我運行outcome為9,if語句仍然運行並分配result的值如1。

問題是,我實際上不確定什么地方出了問題,因為語句中的其他代碼未運行,僅結果整數得到了賦值。

#include <iostream>
#include <algorithm>
#include <ctime>
#include <string>

using namespace std;


int main()
{

    int bankroll=100;
    int bet=1;
    int die1[6]= {1,2,3,4,5,6};
    int die2[6]= {1,2,3,4,5,6};
    int outcome;
    int point;
    int result;
    bool pointroll=false;
    string resulttext;
    random_shuffle(&die1[0],&die1[6]);
    random_shuffle(&die2[0],&die2[6]);

    outcome = die1[0] + die2[0];
cout << "The Outcome is " << outcome << endl;
cout << "The Result is " << result << endl;
    if(outcome==7 || outcome==11)
    {
        resulttext="Win!";
        result=1;
        cout << "Am I running?" << endl;
    }
cout << "The Outcome is " << outcome << endl;
cout << "The Result is " << result << endl;

return 0;}

這是輸出:

The Outcome is 9
The Result is 0
The Outcome is 9
The Result is 1

編輯:我真的不敢相信我怎么忽略了這么簡單的事情。 首先,我沒有指定起始值。 謝謝大家,問題解決了。

如果條件為true,則將result設置為1,那么就很多。 但是在另一種情況下,結果的內容是不確定的-因此它可以是任何內容,甚至允許編譯器在優化過程中隨意對其進行修改。 您應該在其聲明中初始化結果,或者在將其設置為替代值的地方添加一個else分支。

您沒有初始化結果,因此內容為random waste

如果您的IF運行,它將用1覆蓋它; 如果它不運行,則打印該隨機垃圾 (碰巧是1)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM