P5731 【深基5.习6】蛇形方阵 - 输出格式

目录
P5731 【深基5.习6】蛇形方阵 - 输出格式
P5732 【深基5.习7】杨辉三角 - 经典数学
P1957 口算练习题
小知识1:函数的用法
P1308 [ 普及组] 统计单词数
小知识2:C++输入带空格字符串;
P5731 【深基5.习6】蛇形方阵 - 输出格式
123412 13 14511 16 15610987
可以说是水题了,但是全WA,debug了半天,原来是输出格式有毒
AC:
#includeusing namespace std;int a[10][10];int main(){int n;cin>>n;int k=0,i,j;int x=1,y=0;//从a[1][1]开始,方便操作while(k1&&a[x][y-1]==0) //从右到左a[x][--y]=++k;while(x>1&&a[x-1][y]==0) //从下到上a[--x][y]=++k;}for(i=1;i<=n;i++){for(j=1;j<=n;j++)printf("%3d",a[i][j]);printf("\n");//cout<
如果是n*m的蛇形方阵呢?
#include using namespace std;const int N = 110;int a[N][N];int main(){int r,c;cin >> r >> c;int left = 0, right = c - 1;int top = 0, bottom = r - 1;int k = 1;while(left <= right || top <= bottom){for(int i = left; i <= right && top <= bottom; i++)//构造最上面一行{a[top][i] = k++;}top++;for(int i = top; i <= bottom && left <= right; i++)//构造最右侧一列{a[i][right] = k++;}right--;for(int i = right; i >= left && top <= bottom; i--)//构造最下面一行{a[bottom][i] = k++;}bottom--;for(int i = bottom; i >= top && left <= right; i--)//构造最左侧一列{a[i][left] = k++;}left++;}for(int i = 0; i < r; i++){for(int j = 0; j < c; j++) printf("%3d",a[i][j]);cout << endl;}return 0;}
P5732 【深基5.习7】杨辉三角 - 经典数学

11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 1
思路:先定义一个二维数组:a[N][N],略大于要打印的行数 。再令两边的数为 1,即当每行的第一个数和最后一个数为 1 。a[i][0]=a[i][i-1]=1,n 为行数 。除两边的数外,任何一个数为上两顶数之和,即 a[i][j] = a[i-1][j-1] + a[i-1][j] 。
#include#include#include#include#includetypedef long long LL;const int N=1e5+10;using namespace std;int a[21][21];int n;int main(){cin>>n;for(int i=1;i<=n;i++)//从1开始好操作a[i][1]=a[i][i]=1;//易看出,第一列和对角线为1for(int i=1;i<=n;i++){for(int j=2;j
P1957 口算练习题
4a 64 46275 125c 11 99b 46 64
小知识:
函数的用法
函数的格式:
int ( char *, const char * [, ,…] );
1、可以控制精度,还能“四舍五入”
#include#include#includeusing namespace std;int main(){char str1[200];char str2[200];double f1=14.305100;double f2=14.304900;//double f2=14.305000;sprintf(str1,"%20.2f\n",f1);sprintf(str2,"%20.2f\n",f2);cout<
2、可以将多个数值数据连接起来
char str[20];int a=20984,b=48090;sprintf(str,”%3d%6d”,a,b);str[]=”20984 48090”
3、 可以将多个字符串连接成字符串
char str[20];char s1[5]={'A','B','C'};char s2[5]={'x','y','z'};sprintf(str,"%.3s%.3s",s1,s2);str="ABCxyz";
%m.n在字符串的输出中,m表示宽度,字符串共占的列数;n表示实际的字符数 。%m.n在浮点数中,m也表示宽度;n表示小数的位数 。
4、
之后的操作基本跟一样,只不过是函数打印到字符串中(要注意字符串的长度要足够容纳打印的内容,否则会出现内存溢出),而函数打印输出到屏幕上 。
明白用法后,这题直接秒杀:
#include