簡體   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

我想要這樣的輸出,該輸出以三角形順序打印奇數立方體,直到基數10為止。 1 27 27 125 125 125 343 343 343 343 .....

但是我的程序會打印1 27 27 27 125 125 125 125 125 343 343 343 343 343 343 343 .....

它打印出額外的值。

我嘗試了所學到的一切,並添加了額外的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();
}

這就是我要的...

1 27 27 125 125 125 343 343 343 343

編譯器沒有錯誤,只有那些多余的值才會顯示在“輸出”屏幕上。

還行吧?

#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

該解決方案將為您提供一種易於理解的打印方法。 訣竅在於使用足夠的變量進行更新,每行必須打印的次數以及執行立方體的計算:

#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 */
    }
}

這將打印:

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