这个程序中的for循环如何工作? [英] how for loop works in this program ?
本文介绍了这个程序中的for循环如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对此程序及其工作原理进行一些解释.
i want some explanation of this program and how it works.
#include <stdio.h>
int main(void)
{
int num, i, is_prime;
printf("Enter a number: ");
scanf("%d", &num);
is_prime = 1;
for(i = 2; i <= num / 2; i = i + 1)
if((num%i)==0)
is_prime = 0;
if(is_prime==1)
printf(" is prime.");
else
printf("not prime.");
return 0;
}
推荐答案
它基本上是一个简单的试验部门主要发现者.参见此处: http://en.wikipedia.org/wiki/Trial_division [
It''s basically a simple trial division prime finder. See here: http://en.wikipedia.org/wiki/Trial_division[^] which explains it very well.
int num, i, is_prime; // declare three variables, num for user input, i for loop and is_prime used as boolean for the result
//get number from user
printf("Enter a number: ");
scanf("%d", &num);
//set is_prime to true
is_prime = 1;
for(i = 2; i <= num / 2; i = i + 1) //start from 2 and reach until the half the number
if((num%i)==0)// check if any of the number in for loop range successfully divides the number, if so set is_prime to false, as dividable no are not prime
is_prime = 0;
if(is_prime==1) // check if Is_prime was never changed in loop, if s
printf(" is prime.");
else // if the is_prime was changed
printf("not prime.");
大多数时候我们使用
most of time we use
for(i = 2; i <= num / 2; i = i + 1)
if((num%i)==0){
is_prime = 0;
break; }
一旦发现no不为质数,这将停止for循环,保存循环的剩余迭代次数
this stops the for loop as soon as the no is found not to be prime, save remaining iterations of loop
这篇关于这个程序中的for循环如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文