/———————程序3-1 逆序输出———————/
???为什么还是正序输出???——不同的数要加空格。
/*程序3-1 逆序输出*/
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define maxn 105 //what?
int a[maxn];
int main()
{
int x, n=0;
while (scanf("%d", &x) == 1)
a[n++] = x;
for (int i = n - 1; i >= 1;i--)
printf("%d", a[i]);
printf("%d\n", a[0]);
return 0;
}
如果将maxn改为100000(很大的数)
而没有声明在main之外,如下
另:学校作业中全局变量是不被允许的???
数组复制语句memcpy
#include<string.h>
memcpy(b,a,sizeof(int)*k) //a中k个元素复制到b
memcpy(b,a,sizeof(double)*k)
memcpy(b,a,sizeof(a)) a中全部元素复制到b
/———————程序3-2 开灯问题———————/
/*程序3-2 开灯问题*/
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#define maxn 101000
int a[maxn];
int main()
{
int n, k, first=1;
memset(a, 0, sizeof(a)); //把数组a清零
scanf("%d%d", &n, &k);
for (int j=1;j <= k; j++)
for (int i=1; i <= n; i++) //i每一次都要在内层重置!!!
if (i % j == 0)
a[i] = !a[i];
for(int i=1;i<=n;i++)
if (a[i])
{
if (first)
first = 0;//第一次不输出空格
else
printf(" ");
printf("%d", i);
}
printf("\n");
return 0;
}
memset语句:同时改变数组每一项
注意:是小括号。
memset(a, 0, sizeof(a)); //把数组a清零
/———————程序3-3 蛇形填数———————/
/*程序3-2 开灯问题*/
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#define maxn 20
int a[maxn][maxn];
int main()
{
int n,tot=0,x,y;
memset(a, 0, sizeof(a)); //把数组a清零
scanf("%d", &n);
tot = a[x = 0][y = n-1] = 1; //你就是傻逼
while (tot < n * n)
{
while (x + 1 < n && !a[x+1][y]) {
a[++x][y] = ++tot;
}
while (y - 1 >= 0 && !a[x][y-1]) { //x<0?
a[x][--y] = ++tot;
}
while (x - 1 >= 0 && !a[x-1][y]) {
a[--x][y] = ++tot;
}
while (y + 1 < n && !a[x][y+1]) {
a[x][++y] = ++tot;
}
for (x = 0; x < n; x++){
for (y = 0; y < n; y++)
printf("%3d", a[x][y]);
printf("\n");
}
return 0;
}
教训:数组序列的数>>从零开始
如下是没有想到从零开始的错误代码
/*程序3-2 开灯问题*/
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#define maxn 20
int a[maxn][maxn];
int main()
{
int n, tot = 0, x, y;
memset(a, 0, sizeof(a)); //把数组a清零
scanf("%d", &n);
tot = a[x = n][y = 1] = 1;
while (tot <= n * n)/*while (tot < n * n)*/
{
while (y + 1 <= n && !a[x][y + 1]) {
a[x][++y] = ++tot;
}
while (x - 1 >= 1 && !a[x - 1][y]) { //x<0?
a[--x][y] = ++tot;
}
while (y - 1 >= 1 && !a[x][y - 1]) {
a[x][--y] = ++tot;
}
while (x + 1 <= n && !a[x = 1][y]) {
a[++x][y] = ++tot;
}
}
for (x = 1, y = 1; y <= n; y++)
{
for (x = 1; x <= n; x++)
printf("%3d", a[x][y]);
printf("\n");
}
return 0;
}