C 练习实例69

C 语言教程 · 2019-02-22 11:13:12

题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

程序分析:无。

实例

// Created by www.codercto.com on 15/11/9. // Copyright © 2015年 码农教程. All rights reserved. // #include <stdio.h> void main() { int num[50],n,*p,j,loop,i,m,k; printf("请输入这一圈人的数量:\n"); scanf("%d",&n); p=num; //开始给这些人编号 for (j=0;j<n;j++) { *(p+j)=j+1; } i=0;//i用于计数,即让指针后移 m=0;//m记录退出圈子的人数 k=0;//k报数1,2,3 while(m<n-1)//当退出的人数不大于总人数时,即留下的人数至少是一个人 //这句不能写成m<n,因为假设有8人,当退出了6人时,此时还是进行人数退出,即m++, //这时是7<8,剩下的一个人自己喊1,2,3那么他也就退出了,将不会有输出 { if (*(p+i)!=0)//如果这个人的头上编号不是0就开始报数加1,这里采用的方法是报数为3的人头上编号重置为0 { k++; } if (k==3) { k=0; //报数清零,即下一个人从1开始报数 *(p+i)=0;//将报数为3的人编号重置为0 m++; //退出人数加1 } i++; //指针后移 if (i==n)//这句很关键,如果到了队尾,就要使指针重新指向对头 //并且它只能放在i++后面,因为只有i++了才有可能i==n { i=0; } } printf("现在剩下的人是:"); for (loop=0;loop<n;loop++) { if (num[loop]!=0) { printf("%2d号\n",num[loop]); } } }

以上程序执行输出结果为:

请输入这一圈人的数量:
8
现在剩下的人是: 7号

点击查看所有 C 语言教程 文章: https://codercto.com/courses/l/17.html

查看所有标签

Artificial Intelligence

Artificial Intelligence

Stuart Russell、Peter Norvig / Pearson / 2009-12-11 / USD 195.00

The long-anticipated revision of this #1 selling book offers the most comprehensive, state of the art introduction to the theory and practice of artificial intelligence for modern applications. Intell......一起来看看 《Artificial Intelligence》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具