我在做in 50的凯撒问题集,当我试图转换上感知字母时,使用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);
}发布于 2021-08-01 20:27:39
int (Int)不返回布尔值(0或1值)。如果arg大写,则返回非零int。
这两个条件之间的区别是,一个将返回值与一个比较,另一个将返回值与非零进行比较。
发布于 2021-08-01 20:29:54
当你有一些你认为正确/错误的东西时,千万不要写。
if(thing == true)或
if(thing == false)只管写
if(thing)或
if(!thing)事实证明,isupper()和islower()以及<ctype.h>中的其他isxxx函数对于false/true返回零/非零,但不一定返回0/1。如果isupper('A')返回4,那么if(isupper(argument))将如您所期望的那样工作,但if(isupper(argument) == true)总是失败的。
也请参阅问题9.2中的C常见问题单。
发布于 2021-08-01 20:34:22
将真值(布尔表达式)与真理常量进行比较是不好的风格。
if (isdigit(argv[1][i]) == false) // Bad style
if (!isdigit(argv[1][i])) // Better
if (isupper(argument) == true) // Bad style
if (isupper(argument)) // Better 在isupper的例子中,有一个隐藏的错误。为了成为“真”,C中的非零就足够了。但是true在C中被定义为1。
==/!= true/false还显示了排名第二的布尔人,你也可以做(X == true) == true。将原始状态作为一级公民进行冗余和隐藏。它显示了缺少一点编程知识(但并不严重)。
https://stackoverflow.com/questions/68614084
复制相似问题