If statement running even when not true

后端 未结 3 1624
南方客
南方客 2021-01-29 13:35

I am not sure what I\'m doing wrong here, every time I run it, it goes through the if part even when it\'s not true? So the \'else\' never runs.

#in         


        
相关标签:
3条回答
  • 2021-01-29 14:07

    There is a problem in the syntax of 'if' statement. Following is the corrected code, where '||' stands for 'or':

    if ((choice == "F") || (choice=="f")){
        newNo = numb * 0.2 * 9 + 32;
    }else{
        newNo = (numb - 32) / 1.8;
    }
    
    0 讨论(0)
  • 2021-01-29 14:11

    Change this if statement

    if (choice == "F" or "f"){
    

    to the following

    if (choice == "F" or choice == "f"){
    

    Otherwise the right operand of the operator or

    "f"
    

    is always equal to true because it is converted to the address of the first character of the string literal that evidently is not equal to 0.

    That is your original condition in the if statement looks like

    if (choice == "F" or "f" != nullptr){
    

    and indeed "f" != nullptr

    0 讨论(0)
  • 2021-01-29 14:19

    The problem is your if Statement:

    if (choice == "F" or "f"){
    

    basically, what you say here is: If choise is "F" or if "f". You need to understand: True is everything besides zero (0). "f" is NOT zero, so it is true. You could also wirte (or = ||):

    if (coice == "F" || true)
    

    which is the same like:

    if (true)
    

    So in order for your code to work, you need:

    if (choice == "f" || choice == "F")
    

    That would do what you expect.

    0 讨论(0)
提交回复
热议问题