2013-10-02 54 views
0

我是C++的新手,我真的被困在這個問題: 當用戶輸入2個數字EX:1和2比代碼必須找出是否第一個數字是否與第一個數字相同,問題是該代碼沒有將文本帶來的真或假作爲數字:/ (0 = false 1 = true)如何讓我的功能帶回真或假

代碼在這裏:

#include <iostream> 

/* run this program using the console pauser or add your own getch, system("pause") or input loop */ 

bool GraterFunct(int num1, int num2); 

int main(int argc, char** argv) 

{ 
    std::cout <<" \n Hello there! This is a test to test how good you are with math. \n "; 
    std::cout <<" Now enter G or L (Grater, less) to know if a number is grater or less than the number you choose \n "; 
    char answer [1]; 
    std::cin >> answer; 

    if(answer == "G" || "g") 
    { 
     int number1; 
     int number2; 
     std::cout << "You selected: Grater than, \n"; 
     std::cout << "Now type 2 numbers and see which one is grater than the other one. \n" << std::endl; 
     std::cin >> number1; 
     std::cout << "Your first number: " << number1 << std::endl; 
     std::cout << "Select your second number \n"; 
     std::cin >> number2; 
     std::cout << "The answer is: " << GraterFunct(number1, number2); 
    } 

    return 0; 
} 

bool GraterFunct(int num1, int num2) 
{ 
    if(num1 >= num2) 
    { 
     { 
      return true; 
     } 
    } 
    else 
    { 
     if(num2 >= num1) 
     { 
      return false; 
     } 
    } 
} 

請幫忙!提前致謝!

+0

的http://stackoverflow.com/questions/29383 – us2012

+0

重複它的拼寫爲 「大於」 –

+1

縮短:'布爾GraterFunct(INT NUM1,INT NUM2){返回NUM1> = NUM​​1 ; }' – deepmax

回答

1

要格式化布爾值truefalse可以使用std::boolalpha操縱設置std::ios_base::boolalpha標誌:

std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n'; 

如果你是一個非英語母語者和我一樣,你可能要更改格式這些價值。假設有安裝,你可以只imbue()成流,也可以創建你自己和你想要的任何的true渲染和false語言環境,如合適的語言環境:

#include <iostream> 
#include <locale> 

class numpunct 
    : public std::numpunct<char> 
{ 
    std::string do_truename() const { return "wahr"; } 
    std::string do_falsename() const { return "falsch"; } 
}; 

int main() 
{ 
    std::cout.imbue(std::locale(std::locale(), new numpunct)); 
    std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n'; 
} 

順便說一句,你總是需要驗證您輸入是成功的,例如:

if (std::cin >> number1) { 
    // deal with the successful input here 
} 
else { 
    // deal with the wrong input here 
} 
+0

如果程序的目的是教育,輸入驗證會掩蓋實際的代碼。 – riv

+0

@riv:如果人們不學習如何正確讀取數據,他們將永遠不會檢查!不檢查示例代碼是一個壞主意:我看到太多的生產代碼沒有檢查成功的輸入。 –

+0

嘿傢伙感謝所有的建議,我現在可以使函數返回文本! – Lolechi