gpt4 book ai didi

c - 我们如何在c中的if else条件中使用主函数中的函数返回值。我不想在 Isprime_function 文件中使用 print

转载 作者:行者123 更新时间:2023-11-30 18:52:02 25 4
gpt4 key购买 nike

文件 - Isprime_function.c

#include <stdio.h>
#include "all_header.h"

int isprime(int input)
{
int i, stop = 0;

if(input >= 1)
{
for(i=2; i<=input/2; i++)
{
if(input%i==0)
{
stop = 1;
break;
}
}

if(stop==0 && input!=1)
{
printf("%d is a prime number\n",input);
}
else
{
printf("%d is not a prime number\n",input );
}
}
else if(input == 1)
{
printf("%d is not prime by definition!\n", input);
}
else if(input == 0)
{
printf("%d is not a valid number.\n", input);
}
else
{
printf("%d Please use positive nonzero integers! Try again!\n", input);
}
return 0;
}

文件 - Isprime_main.c

#include <stdio.h>
#include "all_header.h"

int main()
{
int input;

printf("\nPlease Enter a Positive Integer: ");
scanf("%d", &input);

isprime(input);

return 0;
}

文件 - All_header.h

#ifndef PRESENT_VALUE_FUNCTIONS
#define PRESENT_VALUE_FUNCTIONS

int isprime(int input);//check whether number is prime or not.

#endif

我使用以下命令

gcc -Wall -o isprime isprime_main.c isprime_function.c all_header.h

我是编程新手,我有一个小疑问。这个函数工作正常,但在我的 isprime_fuction.c 文件中,我使用“printf”,我不想在函数中使用,我想返回特定值并控制主函数的行为,我该怎么做,因为我想使用这个函数用于获取数字的质因数。

最佳答案

你可以这样做:

文件 - Isprime_function.c

#include <stdio.h>
#include "all_header.h"

int isprime(int input)
{
int i, stop = 0;

if (input > 1)
{
for (i = 2; i <= (input / 2); i++)
{
if ((input % i) == 0)
{
stop = 1;
break;
}
}
if ((stop == 0) && (input != 1)) {
return ISPRIME_YES;
} else {
return ISPRIME_NO;
}
}
else if (input == 1)
{
return ISPRIME_NO_BY_DEF;
}
else if (input == 0)
{
return ISPRIME_INVALID;
}
else
{
return ISPRIME_POSITIVE_ONLY;
}
}

文件 - Isprime_main.c

#include <stdio.h>
#include "all_header.h"

int main()
{
int input, result;

printf("\nPlease Enter a Positive Integer: ");
scanf("%d", &input);

result = isprime(input);
switch (result)
{
case ISPRIME_YES:
printf("%d is a prime number\n", input);
break;

case ISPRIME_NO:
printf("%d is not a prime number\n", input);
break;

case ISPRIME_NO_BY_DEF:
printf("%d is not prime by definition!\n", input);
break;

case ISPRIME_INVALID:
printf("%d is not a valid number.\n", input);
break;

case ISPRIME_POSITIVE_ONLY:
printf("%d Please use positive nonzero integers! Try again!\n", input);
break;
}

return 0;
}

文件 - All_header.h

#ifndef PRESENT_VALUE_FUNCTIONS
#define PRESENT_VALUE_FUNCTIONS

#define ISPRIME_POSITIVE_ONLY -3
#define ISPRIME_INVALID -2
#define ISPRIME_NO_BY_DEF -1
#define ISPRIME_NO 0
#define ISPRIME_YES 1

int isprime(int input); //check whether number is prime or not.

#endif

关于c - 我们如何在c中的if else条件中使用主函数中的函数返回值。我不想在 Isprime_function 文件中使用 print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356536/

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