C语言有一叠卡片,卡片号依次为1到n,并且所有卡片的正面朝上。从卡片号2开始,把凡是偶数的卡片都翻成正面朝下。再从3号卡片开始,把凡是卡片号为3的倍数的卡片都翻一面(即把正面朝上的翻成正面朝下,把正面朝下的翻成正面朝上)。下一步从4号卡片开始,把凡是卡片号为4的倍数的卡片都翻转一次,依次类推。问:最后哪些卡片朝上。 【输入形式】 输入一个整数n,表示卡片的总数,6<=n<450 【输出形式】 用空格分开的多个整数。 【样例输入】 23 【样例输出】 1 4 9 16 #include <stdio.h> void upDown(int *p,int n); int main() { int a[450],x,n; scanf("%d",&n); for(x=1;x<=n;x++) a[x]=1; upDown(a,n); for(x=1;x<=n;x++) if(a[x]==1) printf("%d ",x); } void upDown(int *p,int total) { int x,y; x=2; do { while(y<=total) { y+=x; } x++; }while(x<=total); }
时间: 2023-12-03 11:47:25 浏览: 61
这段代码存在一些问题,比如说upDown函数没有完成卡片翻转的功能,同时在upDown函数中的变量y没有初始化,可能会导致程序出错。以下是一个修正后的代码:
```
#include <stdio.h>
void upDown(int *p, int total);
void flipCards(int *p, int total, int step);
int main() {
int a[450], x, n;
scanf("%d", &n);
for (x = 1; x <= n; x++)
a[x] = 1;
upDown(a, n);
flipCards(a, n, 2);
flipCards(a, n, 3);
flipCards(a, n, 4);
for (x = 1; x <= n; x++)
if (a[x] == 1)
printf("%d ", x);
return 0;
}
void upDown(int *p, int total) {
int x;
for (x = 2; x <= total; x += 2)
p[x] = 0;
}
void flipCards(int *p, int total, int step) {
int x, y;
for (x = step; x <= total; x += step) {
if (p[x] == 1) {
p[x] = 0;
} else {
p[x] = 1;
}
for (y = x + step; y <= total; y += step) {
if (p[y] == 1) {
p[y] = 0;
} else {
p[y] = 1;
}
}
}
}
```
这个程序首先调用upDown函数将所有偶数卡片翻转,然后按照题目描述的规则依次调用flipCards函数将卡片翻转。最后输出正面朝上的卡片编号。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)