简体   繁体   English

C语言的奇数模式

[英]Odd number pattern in C language

Can anyone tell me how to print the following pattern in C:谁能告诉我如何在 C 中打印以下图案:

1
13
135
1357
13579

(From OP comment:) (来自 OP 评论:)

I tried this but it prints each value two times a row:我试过了,但它连续两次打印每个值:

#include <stdio.h> 
#include <stdlib.h> 
int main(void) { 
    int i,j,limit; 
    printf("limit"); 
    fflush( stdout ); 
    scanf("%d",&limit); 
    for(i=1;i<=limit;i++){
        for(j=1;j<=i;j++){
            if(j%2==1){ 
                printf("%d",j); 
            }
        }
        printf("\n"); 
    } 
    return EXIT_SUCCESS; 
}

Your code prints each number twice, once for that value (the odd value) and again on the following value (the even value).您的代码将每个数字打印两次,一次用于该值(奇数),另一次用于下一个值(偶数)。

Better would be to loop over just the odd numbers and avoid that worry (and also avoid the additional test for odd):最好只循环奇数并避免这种担心(同时也避免额外的奇数测试):

#include <stdio.h> 
#include <stdlib.h> 
int main(void) { 
    int i,j,limit; 
    printf("limit"); 
    fflush( stdout ); 
    scanf("%d",&limit); 
    for(i=1;i<=limit;i+=2){
        for(j=1;j<=i;j+=2){
            printf("%d",j); 
        }
        printf("\n"); 
    } 
    return EXIT_SUCCESS; 
}

printf("1 13 135 1357 13579");

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

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