C语言二级刷题---填空题01

函数fun的功能是:统计长整数n的各个位上出现数字1、2、3的次数,并通过外部(全局)变量c1、c2、c3返回主函数。例如,当n=123114350时,结果应该为:c1=3c2=1 c3=2请在程序的下划线处填入正确的内容并把下划线删除,使程序得出正确的结果。

思路:

n = 123114350 ,每通过while循环一次,都会被最后的" n /= 10 "代码减少最右边的一位数字(个位),所以将switch表达式填写为" n % 10 ",每次循环都会提取最右侧数字(个位);

提取后的数字通过常量1.2.3来执行其后面的语句,若不在1.2的语句后使用" break "来跳出循环,则每次遇到大于1或2的数字时,都会对" c1 "或" c2 "进行" ++ "操作。

cpp 复制代码
#include   <stdio.h>
#pragma warning (disable:4996)
int  c1,c2,c3;
void fun(long  n)
{  c1 = c2 = c3 = 0;
   while (n) {
/**********found**********/
      switch(___1___)
      {
/**********found**********/
       case 1:    c1++;___2___;
/**********found**********/
       case 2:    c2++;___3___;
       case 3:    c3++;
      }
      n /= 10;
   }
}
main()
{  long  n=123114350L;
   fun(n);
   printf("\nThe result :\n");
   printf("n=%ld  c1=%d  c2=%d  c3=%d\n",n,c1,c2,c3);
}
填空后:
cpp 复制代码
#include   <stdio.h>
#pragma warning (disable:4996)
int  c1,c2,c3;
void fun(long  n)
{  c1 = c2 = c3 = 0;
   while (n) {
/**********found**********/
      switch(n%10)
      {
/**********found**********/
       case 1:    c1++;break;
/**********found**********/
       case 2:    c2++;break;
       case 3:    c3++;
      }
      n /= 10;
   }
}
main()
{  long  n=123114350L;
   fun(n);
   printf("\nThe result :\n");
   printf("n=%ld  c1=%d  c2=%d  c3=%d\n",n,c1,c2,c3);
}
相关推荐
Nazarick1 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴2 小时前
斐波那契数列题解
算法·leetcode
烟烟Abandon2 小时前
FFmpeg开发基础之 C 语言编译器
c语言·开发语言·ffmpeg
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Zwawa4 小时前
断电后参数为什么全没了:把小车配置安全地存进 Flash
c语言·单片机·嵌入式
Keven_114 小时前
算法札记:有限差分
算法
忙里偷闲学python4 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农4 小时前
11.21程序设计
数据结构·算法
Tisfy5 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6175 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法