[英]How to change program from while loop to for loop?
I understand that while
loops and for
loops have different layouts in order to work.我知道
while
循环和for
循环有不同的布局才能工作。 But I am stuck on how to convert this code to for
loop format.但我坚持如何将此代码转换为
for
循环格式。
How do I change the format while keeping the same output?如何在保持相同输出的同时更改格式?
#include<stdio.h>
int main(){
int n, i =1, sum =0;
do{
printf("enter a positive number to find whether prime or not: ");
scanf("%d",&n);
} while (n<=0);
while (i<=n){
if (n%i ==0) sum+=1; //sum is the validation flag
i+=1;
}
if (sum>2) printf("\nThe number %d is not prime.", n);
else
printf("\nThe number %d is prime.", n);
return 0;
}
A for
loop is like a while
loop, except that the iteration variable initialization and updating are put into the for
header. for
循环类似于while
循环,只是迭代变量的初始化和更新放在for
头中。
The initialization is the declaration int i = 1
before the loop.初始化是在循环之前声明
int i = 1
。 The update is i += 1
(which is usually written as i++
).更新为
i += 1
(通常写为i++
)。 So take out these separate statements and put them into the header.所以把这些单独的语句取出来放到header里。
for (int i = 1; i <= n; i++) {
if (n%i == 0) {
sum++;
}
}
If you mean this do-while loop如果你的意思是这个 do-while 循环
do{
printf("enter a positive number to find whether prime or not: ");
scanf("%d",&n);
} while (n<=0);
then it can be rewritten as a for loop for example the following way.然后它可以重写为 for 循环,例如以下方式。
for ( n = 0; n <= 0; scanf("%d",&n) )
{
printf("enter a positive number to find whether prime or not: ");
}
Pay attention to that this code snippet注意这个代码片段
while (i<=n){
if (n%i ==0) sum+=1; //sum is the validation flag
i+=1;
}
if (sum>2) printf("\nThe number %d is not prime.", n);
else
printf("\nThe number %d is prime.", n);
does not correctly determine whether a number is a prime number.不能正确判断一个数是否为素数。 For example for the number equal to 1 the output will be that the number is a prime number.
例如,对于等于 1 的数字,输出将是该数字是素数。 Change the condition in the if statement like
更改 if 语句中的条件,如
if (sum != 2) printf("\nThe number %d is not prime.", n);
As for the while loop then it can be rewritten the following way至于while循环,则可以用以下方式重写
for ( ; i<=n; i++ ){
if (n%i ==0) sum+=1; //sum is the validation flag
}
Also as the variable i is used only within the loop then it is better to declare it in the for loop like此外,由于变量 i 仅在循环中使用,因此最好在 for 循环中声明它,例如
for ( int i = 1; i<=n; i++ ){
if (n%i ==0) sum+=1; //sum is the validation flag
}
In this case remove the declaration of the variable i from this like在这种情况下,从这里删除变量 i 的声明
int n, i =1, sum =0;
at least like至少喜欢
int n, sum =0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.