c - “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);
}
解决方案
int isupper(int) 不返回布尔值(0 或 1 值)。如果 arg 为大写,则返回非零 int。
这两个条件的区别在于,一个将返回值与一个进行比较,另一个将返回值与非零进行比较。
推荐阅读
- python - 如何在python脚本之间使用termux命令
- c - 为 unsigned short (C) 输出位值
- c# - 如何对具有从外部资源获取信息的静态方法的类进行单元测试
- flutter - 扩展和显示 firebase 用户个人资料信息始终为空
- primefaces - p:selectOneListbox 滚动到预选项目
- c# - 实体框架核心 2.1:无法翻译,将在本地评估
- sas-visual-analytics - 修改日期变量
- angular - 使用动态离子段触发两次 ionChange 事件
- javascript - EyeBall 不会跟随 onMouseMove 事件
- css - 将多个元素放在 CSS 网格的单个区域中