附件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/