今天参加了视源股份的笔试题,真就是别人挖个坑让我挑,我就乖乖的跳,话不多说,分享下我的踩坑记0.0
第一道编程题目:
对一个字符型数组中的数据进行减1操作。
比如输入100,输出99(用c的话,不可以使用atoi等函数)
解题思路:
1)首先计算这个数组的长度
char c[16] = {'\0'};
int len = strlen(c)
2)确定这个数组中后几位是'0',到不是'0'哪一位进行字符减1操作,并退出循环
while(1){
if( (char)((int)c[len - 1] - 1)>= '0' ){
c[len - 1] = (char)((int)c[len - 1] - 1);
break;
else{
len--;
temp++;
}
}
3)判断这个数组中是否有是'0'的字符,如果有将是'0'的部分赋值为'9'
int j = len-temp;
if(temp!=0){
for(j; j<=len;j++ ){
printf("j = %d\n",j);
c[j] = '9';
}
}
4)然后输出就好了
strcpy(pro,c);
printf("output:%s\n",pro);
完整代码如下:
#include <stdio.h>
#include <string.h>
int main()
{
int len;
int j;
int temp = 0;
char c[16] = {'\0'};
char pro[16] = {'\0'};
printf("input:");
scanf("%s",c);
len = strlen(c);
while(1){
if( (char)((int)c[len - 1] - 1)>= '0' ){
c[len - 1] = (char)((int)c[len - 1] - 1);
break;
}else{
len--;
temp++;
}
}
j = len-temp;
if(temp!=0){
for(j; j<=len;j++ ){
printf("j = %d\n",j);
c[j] = '9';
}
}
strcpy(pro,c);
printf("output:%s\n",pro);
return 0;
}
下面说一下我踩的坑:
当时我是这样对字符进行加减操作的
#include <stdio.h>
int main()
{
char c = '1';
c = c + '1'; //对字符进行加1
printf("output:%c\n",(char)c);
return 0;
}
~
运行结果:
错误原因其实看一下 ascii码表就知道了
我想让当前数组下标中的字符加1,如果让他加上'1',其实加上的是49,这样结果就是98,对应的就是'b'字符。
正确操作应该是这样的:
#include <stdio.h>
int main()
{
char c = '1';
c = (char)( (int)c + 1 ); //这样才可以实现字符加1
printf("output:%c\n",c);
return 0;
}
输出结果:
应聘路其修远兮,吾将上下而求索...
菜是原罪,我去刷题了...