2、选做题 函数fun的功能是:将一个无符号整数s的偶数数字取出形成一个新数,构成方式是高位仍在高位,低位仍在低位,将新数作为函数值返回。 函数接口定义:int fun(unsigned int s) 要求:在main函数中输入一个整数,调用fun函数,在main函数中输出结果。 输入样例1: 123456 输出样例1: 246 输入样例2: 2876439 输出样例2: 2864 用C语言写
时间: 2023-06-26 13:07:09 浏览: 59
以下是函数fun的代码实现,通过取余运算和位运算实现取出s的偶数数字:
```c
int fun(unsigned int s) {
int res = 0;
int digit = 0;
while (s != 0) {
digit = s % 10; // 取出最低位数字
if (digit % 2 == 0) { // 判断是否为偶数
res = res << 1; // 左移一位,为新数腾出位置
res += digit; // 将偶数数字加入新数的低位
}
s = s / 10; // 去掉最低位数字
}
return res;
}
```
在主函数中调用该函数,并输出结果:
```c
#include <stdio.h>
int fun(unsigned int s);
int main() {
unsigned int s;
scanf("%u", &s);
int res = fun(s);
printf("%d\n", res);
return 0;
}
```
相关问题
函数fun的功能是将一个无符号整数s的偶数数字取出形成一个新数
以下是一个可能的实现:
```C++
unsigned int fun(unsigned int s) {
unsigned int result = 0;
int digit = 0;
while (s != 0) {
digit = s % 10;
if (digit % 2 == 0) {
result *= 10;
result += digit;
}
s /= 10;
}
return result;
}
```
这个函数首先初始化结果为0,然后循环地将输入数的个位数取出来,判断是否为偶数。如果是偶数,就将其添加到结果中。最后,返回结果。
用C语言写一个程序 2、选做题 函数fun的功能是:将一个无符号整数s的偶数数字取出形成一个新数,构成方式是高位仍在高位,低位仍在低位,将新数作为函数值返回。 函数接口定义:int fun(unsigned int s) 要求:在main函数中输入一个整数,调用fun函数,在main函数中输出结果。 输入样例1: 123456 输出样例1: 246 输入样例2: 2876439 输出样例2: 2864
以下是使用C语言编写的程序实现题目要求:
```c
#include <stdio.h>
int fun(unsigned int s) {
int res = 0;
int weight = 1;
while (s) {
int digit = s % 10;
if (digit % 2 == 0) {
res += digit * weight;
weight *= 10;
}
s /= 10;
}
return res;
}
int main() {
unsigned int s;
printf("请输入一个整数:");
scanf("%u", &s);
int res = fun(s);
printf("%d\n", res);
return 0;
}
```
程序先定义了一个函数`fun`,接受一个无符号整数,将其中的偶数数字取出来组成一个新数,并将这个新数作为函数的返回值。具体实现方式是通过循环取出每一位数字,判断是否为偶数,如果是则加入结果中,最后返回结果即可。
在`main`函数中,程序先读入一个整数,然后调用`fun`函数,将结果输出即可。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](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)