gpt4 book ai didi

C 程序 - 素数

转载 作者:行者123 更新时间:2023-11-30 18:55:17 27 4
gpt4 key购买 nike

判断一个数是否为素数。使用代码块 13.12 执行。编译器GNU GCC 4.7.0

#include <stdio.h>

main()
{
int input,check,count;

printf("Enter the number: ");
scanf("&d",&check);

count=0;
for(check=1;check<=1;check++)
{
if((input%check)==0)
{
count++;
}
}
if(count==2)
{
printf("The number %d is prime",check);
}
else
{
printf("The number %d is not prime",check);
}
}

请注意,没有错误或警告。但即使在给出其他输入后,编译器也会假设数字“2”,并且它说 2 不是素数!!

最佳答案

scanf("&d",&check);

应该是

//     v-- percent, not ampersand
scanf("%d",&check);

或者(可能)

scanf("%d", &input);

...因为读取 input 变量会更有意义。稍后在程序中,

printf("The number %d is prime", check); 

应该是

printf("The number %d is prime\n", input);

因为您正在检查输入,而不是检查。下面同样的两行。最后是循环条件

for(check=1;check<=1;check++)

没有任何意义。循环只会运行一次,并且您不想测试输入是否能被 1 整除。这将有意义

                 // v-- check factors until input
for(check=1;check<=input;check++)

这不是最有效的检查,但它可以帮助您入门。

旁注:原型(prototype)

main()

仅符合 C89。从C99开始,不再包含旧的K&R函数声明方法,而main的正确等效原型(prototype)是

int main(void)

所以当你修复问题时,你应该把它放在那里。

关于C 程序 - 素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28069626/

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