杭电OJ | 1720 格式化输入、字符转整型

笔记:虽然又写麻烦了,不过学到了一些知识

1. 字符“0-9”转整型0-9(如之前的文字提到的,字符串转整型用atoi函数)

char a;
int b = a - '0';    // ascii 码的原理

2. 整型0-9转字符“0-9”(如之前的文字提到的,整型转字符串用itoa函数)

int a;
char b = a + '0';    // ascii 码的原理

1720

Input          Input may contain multiple test cases. Each case contains A and B in one line. A, B are hexadecimal number. Input terminates by EOF.

Output       Output A+B in decimal number in one line.

Sample Input

1 9

A B

a b

Sample Output

10

21

21

#include <stdio.h>
#include <math.h>
#include <string.h>
int convert(char *string, int length);
int main()
{
    char a[20],b[20];
    while(scanf("%s %s",&a,&b)!=EOF){ 
    	int alength = strlen(a);
    	int blength = strlen(b);
        printf("%d\n",convert(a,alength)+convert(b,blength));
	}
    return 0;
}
int convert(char *string, int length){
	int sum = 0;
	int index = 0;
	for(;length!=0;length--,index++){
		int nowdigit;
		if(string[index]=='A'||string[index]=='a'){
			nowdigit = 10;
		}
		else if(string[index]=='B'||string[index]=='b'){
			nowdigit = 11;
		}
		else if(string[index]=='C'||string[index]=='c'){
			nowdigit = 12;
		}
		else if(string[index]=='D'||string[index]=='d'){
			nowdigit = 13;
		}
		else if(string[index]=='E'||string[index]=='e'){
			nowdigit = 14;
		}
		else if(string[index]=='F'||string[index]=='f'){
			nowdigit = 15;
		}
		else{
			nowdigit = string[index]-'0';
		}
		sum = sum + nowdigit*pow(16,length-1); 
	}
	return sum;
}

最简单的当然是用scanf的格式化输入%x...

#include<stdio.h>
int main()
{
    int a,b;
    while(scanf("%x %x",&a,&b)!=EOF){
        printf("%d\n",a+b);
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值