c - 哪种代码更简洁、设计更好?

标签 c loops do-while cs50

附件A

所以这段代码有 printf 函数,并且整数输入存储在字后。这是干净的代码吗?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int input;
    do
    {
        printf("Enter a positive number: \n");
        input = get_int();
    }
    while (input <= 0);
}

附件B

我更喜欢这个,因为行数较少,但是两者相比,最终结果相同吗?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int input;
    do
    {
        input = get_int("Please enter a positive integer: \n");
    }
    while (input <= 0);
}

最佳答案

get_int() 采用格式字符串作为其第一个参数以及必须与格式一致的可选参数。第一个代码具有未定义的行为,因为您没有将正确的参数传递给 get_int()

建议向用户提供更多信息。从 main() 返回 0 也是更好的风格。

#include <stdio.h>
#include <cs50.h>

int main(void) {
    int input;
    while ((input = get_int("Please enter a positive integer: ")) <= 0) {
        printf("The number entered %d is not strictly positive\n", input);
    }
    return 0;
}

关于c - 哪种代码更简洁、设计更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474169/

相关文章:

c++ - 没有匹配的函数可调用 'SDL_UpperBlit'

java - 如何打印随机生成的数字数组中重复项的第一个实例?

excel 2010 vba循环通过声明的变量语法导致编译错误变量未定义

python - 无法使用 Python 循环分页 API 响应

java - 代码不退出 while 循环(试图捕获异常)

c - 难以理解连续的递归调用

时间:2019-03-17 标签:c#opennetcfRegistryHelper.SaveHiveBasedKey

c - C中的双重释放没有错误

java - 如何针对特定情况重复 `try` block ?

c++ - 将 do/while 转换为并行 do/while 循环