简体   繁体   English

编程新手。 试图在 C 中编写一个程序,打印偶数直到 10。无法弄清楚逻辑错误

[英]New to programming. Trying to make a program in C that prints even numbers till 10. Can't figure out the logic error

#include <stdio.h>

main()
{
    int n=10;

    for(int a=n;a>=1;a++)  //for bringing out numbers from 1-10
    {
       int e=a%2; //int e to figure out if the number is even(divisible by 2)
       if(e==0)
        printf("%d\n",a); //printing the even numbers
    }
}

I am new to programming.我是编程新手。 Learning C.学习 C。 Here I am trying to make a program that prints even numbers till 10. Executing this code leads to endless even numbers starting from 10.在这里,我正在尝试制作一个打印偶数直到 10 的程序。执行此代码会导致从 10 开始的无穷无尽的偶数。

Can't seem to figure out the logic error here.似乎无法弄清楚这里的逻辑错误。 Some help, please?请帮忙?

The logic for the for loop is not correct. for 循环的逻辑不正确。

int n = 10;

for(int a = 0; a <= n; a++) {
    if(a%2==0){
        printf(a);
    }
}

Notice that this is stating at 0, because in CS almost all the time the count starts at 0.请注意,这表示为 0,因为在 CS 中几乎所有时间都从 0 开始。

Your loop will never end, it should be:你的循环永远不会结束,它应该是:

for(int a = 1; a <= 10; a++)

The entire program should be like that:整个程序应该是这样的:

#include <stdio.h>

int main(void)
{ 
  for(int a = 1; a <= 10; a++)  //for bringing out numbers from 1-10    
    {
      int e = a % 2; //int e to figure out if the number is even(divisible by 2)
      if(e == 0)
        printf("%d\n", a); //printing the even numbers
    }
}

Output: Output:

2
4
6
8
10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM