c语言控制输出间隔大小,C/C++ 输出间隔控制

C++使用setw(int n)来控制他后面的变量的输出占多少个位置。默认是右对齐。

例子:

#include

using namespace std;

#include

using std::setw;

/*

setw(int n)用来控制输出间隔。

cout<

setw()只对其后面紧跟的输出产生作用

表示'a'共占8个位置,不足的用空格填充。

*/

int main ()

{

int n[ 10 ]; // n 是一个包含 10 个整数的数组

// 初始化数组元素

for ( int i = 0; i < 10; i++ )

{

n[ i ] = i + 100; // 设置元素 i 为 i + 100

}

cout << "Element" << setw( 13 ) << "Value" << endl;

// setw(13)表示后面输出的Value占13个位置,前面不足的用空填充

// 输出数组中每个元素的值

for ( int j = 0; j < 10; j++ )

{

cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;

}

//setw()默认是右对齐的,可以设置左对齐

cout<

cout<<:left setw n endl>

cout<

cout<

cout<

//改回默认对齐,右对齐

cout<<:right setw n endl>

return 0;

}结果:

Element Value

0 100

1 101

2 102

3 103

4 104

5 105

6 106

7 107

8 108

9 109

------------------------------

9 109

------------------------------

9######109##########

------------------------------

######9##########109

Process returned 0 (0x0) execution time : 0.097 s

Press any key to continue.C语言是在输出个数符前面加上数字或者小数点来实现的额,例如printf("%8d",n);这样后面的数n也是占8个位置,默认右对齐,

如果想要左对齐只要在百分号后面加一个减号就行了:printf("%-8d",n);

C语言例子:

#include

int main ()

{

int n[ 10 ]; // n 是一个包含 10 个整数的数组

// 初始化数组元素

int i;//C语中循环变量声明不能写到for循环里面

for (i= 0; i < 10; i++ )

{

n[ i ] = i + 100; // 设置元素 i 为 i + 100

}

printf("%s%13s\n","Element","Value");

// 输出数组中每个元素的值

int j;

for ( j = 0; j < 10; j++ )

{

printf("%7d%13d\n",j,n[j]);

}

printf("------------------------------\n");

printf("%-7d%-13d\n",9,9);

printf("------------------------------\n");

return 0;

}结果:

Element Value

0 100

1 101

2 102

3 103

4 104

5 105

6 106

7 107

8 108

9 109

------------------------------

9 9

------------------------------

Process returned 0 (0x0) execution time : 0.152 s

Press any key to continue.

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值