gpt4 book ai didi

c - 有人可以向我解释这段代码,尤其是 for 循环吗?

转载 作者:行者123 更新时间:2023-11-30 19:28:29 27 4
gpt4 key购买 nike

#include<stdio.h>
#include<conio.h>
#include<process.h>
main()
{
int i,flag = 1,n,newn;
clrscr();
printf("Enter number...");
scanf("%d",&n);
for(newn = 2;newn <= n;newn++)
{
flag=1;
for(i=2;i<=newn/2 ;i++) //what would be the initial value of variable "newn" will be.

{
if(newn % i == 0)
{
flag = 0;
break;
}
}
if(flag == 1)
printf("%d ",newn);
}
getch();
}

第一次迭代时内层for循环的初始值是多少?又为什么是外for这个程序需要循环吗?

最佳答案

此代码打印 2 到您输入的数字之间的所有质数。我重写了代码以使其更清楚它的作用

int main()
{
int flag=1, max_number = 100;
// Flag determines if we have a prime number of not
// flag = 1, prime number found
// flag = 0, no prime number found
printf("Please Enter a number bigger then 2 and press enter : \n");
scanf("%d",&max_number);

printf("List of prime numbers from 2 to %d : \n", max_number);

// Counts from 2 till the halb of the number you entered, since 0 and 1
// are not interesting for us
for(int current_number = 2; current_number <= max_number; current_number++)
{

flag=1;
// Counts from 2 till the half of the current_number and check if its a prime
// number

for(int i = 2; i <= current_number/2 ; i++)
{
//printf("Outer loop : %d Inner Loop %d\n", current_number, i);

// Checks if we have a prime number
if(current_number % i ==0)
{
// No we have not a prime number, quit this one and check next number
flag=0;
break;
}
}

// Prime number found
if(flag==1)
printf("Prime number found: %d \n", current_number);
}

return 0;
}

max_number = 15 的输出为:

 Prime number found: 11                                                                                                                                                             
Outer loop : 12 Inner Loop 2
Outer loop : 13 Inner Loop 2
Outer loop : 13 Inner Loop 3
Outer loop : 13 Inner Loop 4
Outer loop : 13 Inner Loop 5
Outer loop : 13 Inner Loop 6
Prime number found: 13
Outer loop : 14 Inner Loop 2
Outer loop : 15 Inner Loop 2
Outer loop : 15 Inner Loop 3

关于c - 有人可以向我解释这段代码,尤其是 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53896682/

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