如何使用 Dart 打印星形图案
How to print star pattern using Dart
我正在尝试使用实现逻辑代码的 Dart 语言来打印星形图案。我使用现有代码作为缩进,以便星号有一些 space。这是这样做的正确方法吗?
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
这是我在 dartpad 中写的答案,更改 starWidth
以调整星星大小。
想法是获取 star 的字符串,然后每行填充然后打印它。
编辑:更新了每个功能的描述注释
void main() {
const starWidth = 7;
// return `*` or `space` if even/odd
starGenerator(i) => i % 2 == 0 ? "*" : " ";
// just return a string full of `space`
printPad(w) => " " * w;
// cause we need `space` between `*`, length is `w * 2 - 1`,
// return a string build of star
printStars(int w) => List.generate(w * 2 - 1, starGenerator).join('');
for (int row = 1; row <= starWidth; row++) {
// cause our width with space is `starWidth * 2`,
// padding left is `padding = (our width with space - star with with space) / 2`,
// but we only need print left side (/2) so the math is simple
// `padding = width - star with without space`
var padding = starWidth - row;
print("$row:" + printPad(padding) + printStars(row));
}
}
我正在尝试使用实现逻辑代码的 Dart 语言来打印星形图案。我使用现有代码作为缩进,以便星号有一些 space。这是这样做的正确方法吗?
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
void main(){
for(int i = 0 ; i< 7; i++){
var stars='';
for(int j = (7-i); j > 1 ;j--) {
stars += ' ';
}
for(int j = 0; j <= i ;j++){
stars += '* ';
}
print(stars);
}
}
这是我在 dartpad 中写的答案,更改 starWidth
以调整星星大小。
想法是获取 star 的字符串,然后每行填充然后打印它。
编辑:更新了每个功能的描述注释
void main() {
const starWidth = 7;
// return `*` or `space` if even/odd
starGenerator(i) => i % 2 == 0 ? "*" : " ";
// just return a string full of `space`
printPad(w) => " " * w;
// cause we need `space` between `*`, length is `w * 2 - 1`,
// return a string build of star
printStars(int w) => List.generate(w * 2 - 1, starGenerator).join('');
for (int row = 1; row <= starWidth; row++) {
// cause our width with space is `starWidth * 2`,
// padding left is `padding = (our width with space - star with with space) / 2`,
// but we only need print left side (/2) so the math is simple
// `padding = width - star with without space`
var padding = starWidth - row;
print("$row:" + printPad(padding) + printStars(row));
}
}