2016-02-03 65 views
-5

我需要幫助在C中創建一棵聖誕樹,這取決於用戶的輸入。在c中以編程方式創建聖誕樹?

首先,提示用戶在樹上想要的級別數。例如。第一級「*」,第二級「***」。每個級別都增加兩顆星。

有效等級在4和10之間運行。小於4或大於10的任何值都是無效的,將在程序輸出中顯示錯誤消息,並顯示樹的最低級別(4級)。

樹的最後一部分是通過將樹幹與3分的寬度和2分的高度來完成。

這是我的c程序。這是不完整的,我不知道如何繼續前進。我完全困惑。

#include <stdio.h> 
void main() 
{ 
    char choice; 
    int level, levelcount, star, starcount; 



    printf("Do you want to print a Christmas Tree (Y/N)?"); 
    scanf_s(" %c", &choice); 

    if (choice == 'Y') 
    { 
     printf("How tall is your Christmas Tree (Level 4 to 10)?"); 
     scanf_s("%d", &levelcount); 

    starcount = 1; 
    for (level = 1; level <= levelcount; level++) 
    { 
     for (star = 1; star <= starcount; star++) 
     { 
      printf("*"); 
     } 
     printf("\n"); 
    } 
     starcount += 2; 
    } 
    else if (choice == 'N') 
    { 
     printf("Merry Christmas and Goodbye!\n"); 
    } 


} 
+0

請在問題中提供詳細信息。圖像網站可以脫機,這使得這個問題對於未來的讀者來說是無用的(假設這是一個很好的問題)。 – StoryTeller

+0

此外,「我有時間做這件事」不是一個有效的問題描述,你遇到的麻煩究竟是什麼? – StoryTeller

+0

在新程序員中創建文本圖像的這種奇怪的癡迷是什麼?代碼是文本。使用複製和粘貼和*發佈文本*。 – molbdnilo

回答

0

首先,你的代碼是C而不是C++。如果您使用的是C++,則可以使用cincout等函數,但在此使用的是printfscanf

要創建此樹,您將有兩個部分。一部分涉及主樹,另一部分涉及樹幹。在下面的代碼中,我使用了一個變量offset來計算確定樹的中點的一定數量。基本上,每個級別都有奇數的星星。如果你從星數減去偏移量,你會發現中點的數字。從3開始,偏移量爲1. 3 - 1 = 2,這是中點。每增加兩個星級,偏移量必須增加一個。

要打印樹:

#include <stdio.h> 
void main() 
{ 
    char choice; 
    int level, levelcount, star, starcount, offset; 

    printf("Do you want to print a Christmas Tree (Y/N)?"); 
    scanf_s(" %c", &choice); 

    if (choice == 'Y') 
    { 
     printf("How tall is your Christmas Tree (Level 4 to 10)?"); 
     scanf_s("%d", &levelcount); 

     //Check if level is within valid range 
     starcount = 1; 
     offset = 0; 
     if (levelcount < 4 || levelCount > 10) 
     { 
      //Prints default tree (4 levels) 
      for (level = 1; level <= 4; level++) 
     { 
      for(star = 1; star <= starcount; star++) 
      { 
       printf("*"); 
      } 
      printf("\n"); 
      //Adds two stars each level 
      starcount += 2; 
      offset += 1; 
     } 
    } 
     else 
     { 
      //Prints tree with custom levels 
      for (level = 1; level <= levelCount; level++) 
      { 
       for(star = 1; star <= starcount; star++) 
       { 
        printf("*"); 
       } 
       printf("\n"); 
       //Adds two stars each level 
       starcount += 2; 
       offset += 1; 
      } 
     } 

     //Finds out the mid-point of the tree 
     int midpoint = starcount - offset; 

     //Prints the trunk 
     printf("%*s%s\n", offset - 1, "***"); 
     printf("%*s%s\n", offset - 1, "***"); 

    } 
    else if (choice == 'N') 
    { 
     printf("Merry Christmas and Goodbye!\n"); 
    } 
} 

爲主幹部分,因爲它是在3星級的固定寬度,而且只有兩個層次,一個循環是不完全必要的,但它會很好包括它。 %*s是一個特定的修飾符,用於在左側打印一些額外的空格,以便它位於樹的中點。

更多關於填充用空格用C check this answer by Bill the Lizard。答案下面的評論之一將顯示我如何設法打印由變量offset - 1確定的一定數量的空格。