gpt4 book ai didi

无法在 C 中正确获得钻石形状

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:29 25 4
gpt4 key购买 nike

我正在做一个 c 练习,用一个函数用 '#' 做一个菱形。我的代码:

    #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");
}}

输出是这样的:

Losangle: 5
#
# #
# # #
# # # #
# # # # #
# # # #
# # # #
# # # #
# # # #

是什么让底部的“#”不递减?这行错了吗 (for(hashtag1 = (n-1); hashtag1 > 0; hashtag1--)) ??顺便说一句,我也接受提高代码效率的技巧。

最佳答案

问题:

倒三角for循环每次从n-1迭代到0,不管j' s值。

解决方案:

n-1j 之间迭代将导致哈希符号的数量在每次迭代中减少。

改变这一行:

for(hashtag1 = (n-1); hashtag1 > 0; hashtag1--){

for(hashtag1 = (n-1); hashtag1 > j; hashtag1--){

关于无法在 C 中正确获得钻石形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com