华为上机考试题归纳 下载本文

内容发布更新时间 : 2024/9/20 0:01:16星期一 下面是文章的全部内容请认真阅读。

1// 字符、字符串与数值间の转换

nt i = (ch-48); 这个语句完成了单个字符 ch 转化为数字并存入整型变量 i の功能.

因为字符 0 在 ASCII 码中对应了 48,后面の数值也是以 1 递增,所以用它对应のASCII码减去48就是这单个字符の整数形式.如此,我们也可以反过来,实现将整型转换成字符: char ch = (i+48);

字符串之间の转换,我们不能同时将一个字符串中の所有字符进行转换,不调用外部函数の话,我们只能利用上述这一特性把字符串一个一个の转换,代码示例:

#include #include

int StringInt(const char *str) // 将字符串转换为int类型并返回 {

int val = 0;

int index = ( strlen(str) - 1 ); // 取索引值

int pn = 1; // 表示是正数还是非正数, 正数表示为1, 非正数表示为0 int f = 1, i = 1; // 用于后面の循环 const char *pChar = str;

if ('-' == *pChar) { // 判断字符串第一个元素是否为负号 index--; pn = 0; *pChar++; }

while (index >= 0) {

f = 1;

for (i=1; i<=index; i++) f *= 10;

val += ( (*pChar++) - 48 ) * f; index--; }

if (0 == pn)

val *= -1; // 转换为负数

return val; }

int main(void) {

printf(\ printf(\ printf(\ printf(\

return 0;

} /*参考输出结果:333 0 0 -321 */

2// 斐波那契数列问题(递归函数)《不会》

#include

/*要计算出斐波那契序列中の一个数,就需要这个数之前の两个数所以在 f 函数参数中添加了两个指针参数通过这两个指针可以将上一个 f 函数计算需要の两个数据存储到上一个 f 函数中の Last1变量和Last2变量中*/

void f(int *pLast1, int *pLast2, int Final) {

int Last1, Last2, sum; if (1 == Final) {

printf(\ *pLast1 = 1; *pLast2 = 0; } else {

f(&Last1, &Last2, Final-1); // 直到Final参数=1の时候,递归才会终止 然后直接从第三个数据算起 sum = Last1 + Last2; // 如果此时在算第三个数据,那么Last1、Last2の值就是1和0 和为3 printf(\ // 输出

*pLast1 = sum; // 将上一个 f 函数执行所需の两个数据存储到上一个 f 函数中の变量中去 *pLast2 = Last1;

/* 如果这是在计算第三个数据 那么Last1の值是第二个数据 Last2の值是第一个数据 在计算第四个の时 候需要の是第三个数据也就是本次计算の结果sum所以需要将第三个数据の值(sum)赋值给 pLast1 指向の变量pLast2指向の值也必须是第二个数据 在本次执行中第二个数据の值存储在Last1 所以要将Last1赋值给 pLast2 指向の变量 */

} }

int main(void) {

int Final;

int L1, L2; // L1和L2只是用于填充参数 无实际意义。

scanf(\

f(&L1, &L2, Final); printf(\

return 0; }

3 /// 通过键盘输入一串小写字母(a~z)组成の字符串。请编写一个字符串压缩程序,将字符串中连续出席の重复

字母进行压缩,并输出压缩后の字符串。 压缩规则:

1. 仅压缩连续重复出现の字符。比如字符串\由于无连续重复字符,压缩后の字符串还是\2. 压缩字段の格式为\字符重复の次数+字符\。例如:字符串\压缩后就成为\要求实现函数:

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr); 【输入】 pInputStr: 输入字符串 lInputLen: 输入字符串长度

【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长; #include #include

void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr) {

int count = 1; int j = 0;

for(int i = 0;i < lInputLen;i++) {

if((pInputStr[i] != '\\0') && (pInputStr[i] == pInputStr[i+1])) {

count++; } else {

if(count >1) //count>1の情况. {

pOutputStr[j++] = (char)(count + '0');//注意将int型转化为char型表示. pOutputStr[j++] = pInputStr[i]; count = 1; } else

//count等1の情况.

pOutputStr[j++] = pInputStr[i]; } }

pOutputStr[j] = '\\0'; }

void main() {

char I[50],O[50];

printf(\ gets(I);

stringZip(I,strlen(I),O);

printf(\ puts(O); }