c语言 - 为什么我的布尔函数需要"return true"才能正常工作?



我正在学习CS50x课程。问题集2的作业是凯撒算法。

我正常上班了。但有一件事让我感到困惑:

bool onlydigits函数-它需要最终返回true才能正常工作。我在谷歌上搜索,人们说必须有一个默认的返回值,好吧,我理解。

但是当我把它从TRUE切换到FALSE时,程序只是把所有的命令行参数都当作FALSE。因此程序无法运行。

我是算法和编程的新手。请帮我理解这部分。

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
bool only_digits(string s);
char rotate(char c, int n);
int main(int argc, string argv[])
{
// Make sure program was run with just one command-line argument
// Also make sure every character in argv[1] is a digit
if (argc < 2 || argc >2 || only_digits(argv[1]) == false)
{
printf("Usage: ./caesar keyn");
return 1;
}
// Convert argument to int
int x = atoi(argv[1]);
// Prompt the user
string plaintext = get_string("plaintext: ");
// Encrypt the plaintext
printf("ciphertext: ");
for (int i = 0, len = strlen(plaintext); i < len; i++)
{
char cipher = rotate(plaintext[i], x);
printf("%c", cipher);
}
printf("n");
}
// Function check if only digit
bool only_digits(string s)
{
for (int i = 0, len = strlen(s); i < len; i++)
{
if (isdigit(s[i]))
{
while(s[i] == '')
return true;
}
else
{
return false;
}
}
return true; /* This part, I dont understand why */
}
// Function rotate
char rotate(char c, int n)
{
if (isalpha(c))
{
if (isupper(c))
{
c = 'A' + (c - 'A' + n) % 26;
return c;
}
else c = 'a' + ((c - 'a' + n) % 26);
return c;
}
else return c;
}

所以我将在这里讨论一个函数,即具有return true:的函数

bool only_digits(string s)
{
for (int i = 0, len = strlen(s); i < len; i++)
{
if (isdigit(s[i]))
{
while(s[i] == '')
return true;
}
else
{
return false;
}
}
return true; /* This part, I dont understand why */
}

所以你问if (isdigit(s[i]),然后你开始一个while循环,它在s[i] != ''时终止,一旦你进入if体,这就已经是真的了。

您要做的是检查字符串中是否有任何非数字。类似的东西

bool only_digits(string s)
{
for (int i = 0, len = strlen(s); i < len; i++)
{
if (!isdigit(s[i]))
return false;
}
return true; /* if we didn't find a non-digit, we're fine */
}

最新更新