gpt4 book ai didi

c - 制作验证函数以判断输入的数字是否为正数

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:10 24 4
gpt4 key购买 nike

/* 这只是我试图为计算房间面积的更大程序制作的一个函数。当答案 <= 0 时,我想让函数接管,但是在编译它时我总是遇到一些参数错误。任何帮助将不胜感激。*/

#include <stdio.h>
int validInput(double len);
int main(void)
{
double len ;
int check;
printf("\nEnter length of room in feet:");
scanf("%lf", &len);
check = validInput();

return 0;

}

int validInput(double len)
{
int check;
if (len <= 0 )
printf("\nNumbers entered must be positive.");
return check;
}

最佳答案

这一行:

check = validInput();

缺少参数。建议:

check = validInput( len );

当然,代码应该检查返回值,而不是参数值,从调用 scanf() 以确保操作成功。在这种情况下,返回值应为 1。任何其他返回值都将指示发生错误。

关于 validInput() 函数:

变量 check 从未被初始化为任何特定值。建议:

int validInput(double len)
{
int check = 1; // indicate valid

if (len <= 0 )
{
check = 0; // indicate not valid
printf("\nNumbers entered must be positive.\n");
}

return check;
}

注意:调用 printf() 时尾部的 \n 是强制立即输出文本,而不是在内部 stdout< 中设置 缓冲直到程序退出,此时它会被输出。

将适当的错误检查合并到 main() 函数中会导致:

#include <stdio.h>   // scanf(), printf()
#include <stdlib.h> // exit(), EXIT_FAILURE

int validInput(double len);

int main(void)
{
double len ;
int check;

printf("\nEnter length of room in feet:");
if( 1 != scanf("%lf", &len) )
{ // then scanf failed
perror( "scanf for length of room, in feet, failed" );
exit( EXIT_FAILURE );
}

// implied else, scanf successful

check = validInput( len );

printf( "the user input was %s\n", (check)? "valid" : "not valid");

return 0;

} // end function: main

关于c - 制作验证函数以判断输入的数字是否为正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com