我正在做运动,用'#'做一个钻石形状,使用一个功能.我的代码:
#include <stdio.h>
//Declare function
void losangle(int n);
//main
int main(void){
int n;
do {
printf("Altura do triangulo: ");
scanf("%d", &n );
} while( n % 2 == 0);
losangle(n);}
//function
void losangle(int n){
int i, hashtag, spaces, j, spaces1, hashtag1;
//triangle
for(i = 0; i < n; i++){
for(spaces = 0; spaces < (n-i); spaces++){
printf(" ");}
for(hashtag = 0; hashtag < (i+1);hashtag++){
printf("# ");}
printf("\n");}
//inverted triangle
for(j = 0; j < (n - 1); j++){
for(spaces1 = 0; spaces1 < (j+2); spaces1++){
printf(" ");}
//not working !!!
for(hashtag1 = (n-1); hashtag1 > 0; hashtag1--){
printf("# ");}
printf("\n");
}}
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
Losangle: 5
#
# #
# # #
# # # #
# # # # #
# # # #
# # # #
# # # #
# # # #
Run Code Online (Sandbox Code Playgroud)
是什么让'#'在底部没有减少?这行是错误的(for(hashtag1 =(n-1); hashtag1> 0; hashtag1--))?? 顺便说一下,我也接受提高代码效率的技巧.
问题:
倒三角形for循环从每次迭代n-1到迭代0,无论其j值如何.
解:
在n-1to 之间迭代j将导致散列符号的数量在每次迭代时减少.
改变这一行:
for(hashtag1 = (n-1); hashtag1 > 0; hashtag1--){
Run Code Online (Sandbox Code Playgroud)
至
for(hashtag1 = (n-1); hashtag1 > j; hashtag1--){
Run Code Online (Sandbox Code Playgroud)