打印數字菱形

使用循環結構打印出以下圖形:ios

      1spa

    212code

  32123blog

4321234io

  32123 class

    212stream

      1循環

參考程序以下:程序

#include<iostream>
using namespace std;

int main()
{
  for(int i=-3;i<=3;i++) //控制輸出的行數
  {
    int k=abs(i);
    for(________) //控制輸出的空格數
      cout<<' ';
    for(________) //控制輸出的數字
      cout<<____;
    cout<<endl;
  }
  system("pause");
  return 0;
}

答案:di

#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){

    for(int i = -3; i <= 3; i++){
        int k = abs(i);
        for(int j = 0; j <= k; j++){
            cout<<' ';
        }
        for(int j = k-3; j <= 3-k; j++ ){
            cout<<abs(j)+1;
        }
        cout<<endl;
    }
    
    system("pause");
    return 0;
}

或者:

#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){

    for(int i = -3; i <= 3; i++){
        int k = abs(i);
        for(int j = 0; j <= k; j++){
            cout<<' ';
        }
        for(int j = 0; j < 7-2*k; j++ ){
            cout<<abs(3-k-j)+1;
        }
        cout<<endl;
    }
    
    system("pause");
    return 0;
} 

拓展:

#include<iostream>
#include<stdlib.h>
using namespace std;
int main(){

    for(int i = -2; i <= 2; i++){
        int k = abs(i);
        for(int j = 0; j <= 2 * k; j++){
            cout<<' ';
        }
        for(int j = 0; j < 9 - 4 * k; j++ ){
            cout<<abs(4 - 2 * k - j) + 1;
        }
        cout<<endl;
    }
    system("pause");
    return 0;
} 
相關文章
相關標籤/搜索