[英]Unusual Behaviour of printf statement inside loop
I am new to programming world, I made a program to check if the given number is prime or not, but it is showing unusual behaviour.我是编程世界的新手,我做了一个程序来检查给定的数字是否是素数,但它表现出不寻常的行为。
My code:我的代码:
#include <stdio.h>
void main()
{
int n;
printf("Enter n:");
scanf("%d", &n);
for (int i = 0; i <= n - 1; i++)
{
if (n % i == 0)
{
printf("n is not a prime number!");
break;
}
if (i == n - 1)
{
printf("n is prime!");
}
}
}
Expected Output:预期 Output:
Enter n:5
n is prime!
Actual Output:实际 Output:
Enter n:5
Reference Screenshot参考截图
Using VS Code and MinGW.使用 VS Code 和 MinGW。 Thanks in Advance提前致谢
For starters according to the C Standard the function main without parameters shall be declared like对于根据 C 标准的启动器,不带参数的 function main 应声明为
int main( void )
In this for loop在这个 for 循环中
for (int i = 0; i <= n - 1; i++)
{
if (n % i == 0)
//..
there is division by zero when i
is equal to 0.当i
等于 0 时,除以零。
Apart from this any number prime or not prime is divisible by 1. So in any case the approach with this for loop is incorrect.除此之外,任何数素数或非素数都可以被 1 整除。所以无论如何,使用这个 for 循环的方法是不正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.