简体   繁体   English

一些值会使我不需要的i(i​​ = 0; i <10; i ++)额外打印。 在C中使用for循环时

[英]Some values are printing extra times the i (i = 0; i < 10; i++) that i don't want . While using for loop in C

I want an output that prints cube of odd numbers printing in a triangular order up to base number 10, like this. 我想要这样的输出,该输出以三角形顺序打印奇数立方体,直到基数10为止。 1 27 27 125 125 125 343 343 343 343 ..... 1 27 27 125 125 125 343 343 343 343 .....

but my program prints 1 27 27 27 125 125 125 125 125 343 343 343 343 343 343 343 ..... 但是我的程序会打印1 27 27 27 125 125 125 125 125 343 343 343 343 343 343 343 .....

it prints extra values. 它打印出额外的值。

I tried whatever possible that I learned, and also adding extra for loops... 我尝试了所学到的一切,并添加了额外的for循环...

#include<stdio.h>
#include<conio.h>
void main()
{
    clrscr();
    int a;
    int i,j;
    a=1;
    for(i=0;i<10;i++)
    {

        for(j=0;j<i;j++)
        {
            if(i%2!=0)
            {
                a=i*i*i;
                printf("%d  ",a);
            }

        }
        printf("\n");
     }
    getch();
}

This is what I want... 这就是我要的...

1 27 27 125 125 125 343 343 343 343

No errors by the compiler, only those extra values printing on the Output screen. 编译器没有错误,只有那些多余的值才会显示在“输出”屏幕上。

this is ok? 还行吧?

#include<stdio.h>
#include<conio.h>

void main()
{
    int a = 1;

    for (int i = 1; i < 10; i+=2)
    {
        for (int j = 0; j < i - i/2; j++)
        {
                a = i * i * i;
                printf("%d  ", a);
        }
        printf("\n");
    }
    getchar();
}

1 27 27 125 125 125 343 343 343 343 729 729 729 729 729 1 27 27 125 125 125 343 343 343 343 729 729 729 729 729

This solution will give you an easy to understand way to do the printing. 该解决方案将为您提供一种易于理解的打印方法。 The trick consists in using enough variables to update, the number of times you have to print at each line, and the computations to do de cubes: 诀窍在于使用足够的变量进行更新,每行必须打印的次数以及执行立方体的计算:

#include <stdio.h>

int main()
{
    int a = 1, line;
    for (line = 0; line < 10; line++) {
            int cube = a*a*a, item_in_line;
            char *sep = "";  /* no separator at the beginning */
            for (item_in_line = 0; 
                 item_in_line <= line; 
                 item_in_line++) {
                    printf("%s%d", sep, cube);
                    sep = ", ";  /* from now on, we print commas */
            }
            printf("\n");
            a += 2; /* get next number to cube */
    }
}

This will print: 这将打印:

1
27, 27
125, 125, 125
343, 343, 343, 343
729, 729, 729, 729, 729
1331, 1331, 1331, 1331, 1331, 1331
2197, 2197, 2197, 2197, 2197, 2197, 2197
3375, 3375, 3375, 3375, 3375, 3375, 3375, 3375
4913, 4913, 4913, 4913, 4913, 4913, 4913, 4913, 4913
6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859, 6859

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

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