首页 > 解决方案 > “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 key\n");
                return 1;
            }
        }
    }
    else
    {
        printf("Usage: ./caesar key\n");
        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: %s\n", ciphertext);
}

标签: ccs50

解决方案


int isupper(int) 不返回布尔值(0 或 1 值)。如果 arg 为大写,则返回非零 int。

这两个条件的区别在于,一个将返回值与一个进行比较,另一个将返回值与非零进行比较。


推荐阅读