[英]Why is my output showing twice the limit I have entered?
Write a C program to print all even numbers between 1 to 100. - using while loop
编写一个 C 程序来打印 1 到 100 之间的所有偶数。 - 使用 while 循环
#include<stdio.h>
int main(int argc, char const *argv[])
{
int a=0,Even,Go;
printf("Enter the Value:\n");
scanf("%d",&Go);
while(a<=Go)
{
Even=a*2;
printf("%d\t",Even);
a++;
}
return 0;
}
OutPut:输出:
Enter the Value:
20
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 %
As pointed out in the comments, your while
condition is not based on the numbers that you're printing.正如评论中所指出的,您的
while
条件不是基于您正在打印的数字。 You're testing the number and then doubling it when printing.您正在测试数字,然后在打印时将其加倍。
Instead, you can simply increment by 2 so you test the same numbers you're printing.相反,您可以简单地增加 2,以便测试您正在打印的相同数字。
Since the numbers should be between 1 and Go
, you should initialize a
to 2
rather than 0
.由于数字应该介于 1 和
Go
之间,因此您应该将a
初始化为2
而不是0
。
#include<stdio.h>
int main(int argc, char const *argv[])
{
int a=2,Even,Go;
printf("Enter the Value:\n");
scanf("%d",&Go);
while(a<=Go)
{
printf("%d\t",a);
a += 2;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.