我只是想知道和混淆为什么我的输出搞砸了.代码如下.我是初学者,请原谅我缺乏技巧.任何帮助将非常感谢.
#include <stdio.h>
int main(int argc, char *argv[])
{
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= i; j++)
{
printf("*");
}
printf("\t");
for (int k = 1; k <= 11-i; k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出这个输出:
use*_*023 13
精度和宽度字段可用于格式化.精度将打印到指定的字符数,宽度将至少打印指定的字符数.在任一字段中使用星号都允许使用可变数量字符的参数.
#include <stdio.h>
int main( void) {
char asterisk[] = "***********";
for (int i = 1; i <= 10; i++)
{
printf ( "%.*s", i, asterisk);//print up to i characters
printf ( "%*s", 15 - i, " ");//print at least 15 - i characters
printf ( "%.*s", 11 - i, asterisk);
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
chu*_*ica 13
...为什么我的输出搞砸了(?)
代码使用的选项卡'\t'
只与下一个制表符对齐 - 通常每8列,所需的星号超过8.
通过明智地使用'-'
标志,字段宽度和精度,可以简化代码以打印字符数组.
#include <stdio.h>
#include <string.h>
int main(void) {
int n = 10;
char stars[n];
memset(stars, '*', n);
for (int i = 0; i < n; i++) {
// +------------- - flag: pad on right
// |+------------ field width: min characters to print, pad with spaces
// || +--------+- precision: max numbers of characters of the array to print
printf("%-*.*s %.*s\n", n, i + 1, stars, n - i, stars);
// | ^^^^^ ^^^^^ precision
// +--------------------- field width
}
}
Run Code Online (Sandbox Code Playgroud)
产量
* **********
** *********
*** ********
**** *******
***** ******
****** *****
******* ****
******** ***
********* **
********** *
Run Code Online (Sandbox Code Playgroud)
注意:stars
不是字符串,因为它缺少空字符.使用精度"%s"
允许printf()
使用简单的字符数组.数组中的字符被写入(但不包括)终止空字符.
制表位不是固定宽度的空间(例如,与4个空格或8个空格相同),这意味着输出设备应将插入符号(或打印头)移动到表格数据的下一列位置.这些列位置是固定的固定间隔,这就是为什么\t**
并**\t
具有不同的打印宽度:
String Output:
"\t**a" " **a" (7 wide)
"**\ta" "** a" (5 wide)
Run Code Online (Sandbox Code Playgroud)