“if(isupper(argument)==true)”和“if(isupper(argument))”有什么区别?注意:参数是我程序中的任何字符

我正在做CS50的凯撒问题集,当我尝试移动大写字母时,if (isupper(argument) == true)用来检查我想要移动的字符是否为大写,它没有用,它认为大写字母实际上不是大写。当我将其切换到 时if (isupper(argument)),程序正确地移动了大写字母。这两种格式有什么区别吗?这是我使用的代码(我指的是 for 循环中的代码):

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    //Check wether there is only 1 command line argument
    if (argc == 2)
    {
        //Check if there is any character that's not a digit
        for (int i = 0; i < strlen(argv[1]); i++)
        {
            if (isdigit(argv[1][i]) == false)
            {
                printf("Usage: ./caesar keyn");
                return 1;
            }
        }
    }
    else
    {
        printf("Usage: ./caesar keyn");
        return 1;
    }
    
    //Convert key to an int
    int key = atoi(argv[1]);
    
    //Prompt plaintext
    string plaintext = get_string("plaintext: ");
    string ciphertext = plaintext;
    
    //Shift ciphertext's characters by the amount of "key"
    for (int i = 0; i < strlen(plaintext); i++)
    {
        //If it isn't a letter, do nothing
        if (isalpha(plaintext[i]) == false)
        {
            ciphertext[i] = plaintext[i];
        }
        else
        {
            //If it's uppercase
            if (isupper(plaintext[i]) == true)
            {
                //Convert ASCII to alphabetical index
                plaintext[i] -= 'A';
                //Shift alphabetical index
                ciphertext[i] = (plaintext[i] + key) % 26;
                //Convert alphabetical index to ASCII
                ciphertext[i] += 'A';
            }
            //If it's lowercase
            else if (islower(plaintext[i]))
            {
                //Convert ASCII to alphabetical index
                plaintext[i] -= 'a';
                //Shift alphabetical index
                ciphertext[i] = (plaintext[i] + key) % 26;
                //Convert alphabetical index to ASCII
                ciphertext[i] += 'a';
            }
        
        }

    }
    
    //Print ciphertext
    printf("ciphertext: %sn", ciphertext);
}

回答

int isupper(int) 不返回布尔值(0 或 1 值)。如果 arg 是大写的,它返回一个非零的 int。

两种情况的区别在于,一种将返回值与 1 进行比较,另一种将返回值与非零进行比较。


回答

当你有一些你认为是真的/假的东西时,永远不要写

if(thing == true)

或者

if(thing == false)

写就好了

if(thing)

或者

if(!thing)

事实证明,isupper()islower()和的isxxx功能其余<ctype.h>归还零/非零假/真,但并不一定是0/1。如果isupper('A')返回,例如 4,if(isupper(argument))则将按预期工作,但if(isupper(argument) == true)总是会失败。

另请参阅C FAQ 列表中的问题 9.2。


以上是“if(isupper(argument)==true)”和“if(isupper(argument))”有什么区别?注意:参数是我程序中的任何字符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>