2017-09-13 51 views
-1

我想做布爾方程如5 < 7將是true,並且7 < 5將會是這樣的錯誤。代碼塊布爾錯誤

當我執行它的代碼詢問A的價值,我把一個值,然後輸入但他不問B的價值..和和之後出現的隨機數..

現在我再次啓動它,我在一個值,那麼它所需要的b的值是1型,I型2,但仍回答是呈現像AB

int main() { 
    bool a; 
    bool b; 

    cout << "enter value for a" << endl; 
    cin>>a; 
    cout << "enter value for a" << endl; 
    cin >> b; 
    bool e = a < b; 
    cout << "sum is" << e; 
    return 0; 
    getch(); 
} 
+0

請務必使用'code block'來發布您的代碼示例,不要只是在這裏截圖文本編輯器並粘貼圖像。 –

+0

'bool'不會像5或7那樣取值,所以你的'a'和'b'不會有你期望的值。 –

+0

附註:'return'後的任何語句都不會被執行。 – user0042

回答

0

bool只接受兩個條件,要麼是0,要麼是非零值,而是0值,它被評估爲1(真)。要添加整數,您應使用關鍵字int,對於十進制數字,請使用doublefloat

對於您的情況,您必須聲明ab爲整數類型而不是bool。您的布爾變量e很好,它接收變量a是否小於變量b的條件。你的最後std::cout不應該要求他們的總和,因爲e不用於總結他們,但從a < b得到的條件。

#include <iostream> 

int main() { 
    int a; 
    int b; 

    std::cout << "enter value for a " << std::endl; 
    std::cin >> a; 
    std::cout << "enter value for b " << std::endl; 
    std::cin >> b; 

    bool e = a < b; 
    std::cout << "a < b is: " << e << std::endl; 
    return 0; 
} 
+0

寫我明白它:) –

+0

Walaikum -O-ASSALAM,是它幫助我很多。我有很多問題也要問,我會在你的問題中給你加上標籤:) @V G –

+0

哈哈沒問題,只要適用就做。如果我有資格,我會回答。 –

1

你可能想這樣的:

#include <iostream> 

using namespace std; 

int main() { 
    int a; // int instead of bool 
    int b; // int instead of bool 

    cout << "enter value for a " << endl; 
    cin >> a; 
    cout << "enter value for b " << endl; 
    cin >> b; 

    bool e = a < b; 
    cout << "a < b is " << e << endl; // prints 1 for true and 0 for false 
    return 0; 
    // getch(); // useless because it will never be executed after return 0; 
} 

看解釋的評論國家。

+0

@PaulR問題有點不清楚,但我添加了第二個解決方案 –

+1

@PaulR是的,您可能是對的,我編輯了答案 –

+0

謝謝夥計們,對不起,Em編程中的新內容也對此網站:)忽略我的錯誤 –