2008年10月17日 星期五

C++菱形範例

此為幫人代工之物,我猜以後還會有類似的東西,先記下

#
include <cstdlib>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
int h,i,j,k,v;
cout << "請輸入數字:"<<endl;
cin >> v;
for(i=1;i<=v*2-1;i++){
for(j=0;j<abs(v-i);j++){
cout<<" ";
}
h=(i<=v)?(i*2-1):((v*2-i)*2-1);
for(k=0;k<h;k++){
cout<< "*" ;
}
cout << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
其他解:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n=5,i=0,j=-1;
while(++i<n*2){
j=-1;
while(++j<n*2)
printf((j>abs(n-i)-1&&j<n*2-1-abs(n-i))?"*":" ");
printf("\n");
}
system("pause");
}
一行版:
int main()
{
int n=4,i=-1;
char output[n*2+2];
output[n*2+1]=0;
while(i++<n*2)
printf("%s\n",memset(memset(output,32,n*2+1)+abs(n-i),42,(n-abs(n-i))*2+1)-abs(n-i));
system("pause");
}




2 則留言:

  1. *
    **
    ***
    ****
    ***
    **
    *
    請問那這樣的程式該怎樣寫
    有Microsoft Visual C++ 6.0的寫法嗎

    回覆刪除
  2. 先拆成兩段
    1 2 3 4 3 2 1-> 1 2 3 4 跟 3 2 1
    那麼接下來就很簡單的用for或while了

    回覆刪除