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);
}
相关推荐
aaaameliaaa3 小时前
字符函数和字符串函数
c语言·笔记·算法
夜月yeyue3 小时前
AUTOSAR CP 从上电到 Runnable
c语言·网络·tcp/ip·车载系统
城管不管4 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯5 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡5 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯5 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang5 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9855 小时前
高进度算法模板速记(待完善)
java·前端·算法
小羊先生car6 小时前
RTOS-F429-HAL-绝对延时和相对延时(2026/7/31)
c语言·rtos
土豆.exe8 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法