I am writing a program to calculate sum of 2 variables. One of these is a number from 1 to 10, and the other is one letter of the alphabet (uppercase) which has value corresponding to its order. The input can be only number, only letter or both.
For instance:
Input
10 7
C 8
E D
9 F
Output
17
11
9
15
This is my code (This question suppose to be posted on codereview, but for some reason I can't format code right way on codereview. Please forgive me).
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
char a[3], b[3];
int m,n;
//these variables hold the value of grade after converted
scanf("%s%s", a, b);
if (a[1]!='\0')
{
//this is because only number 10 has 2 digits
m=10;
}
else if (a[0]>=49 && a[0]<=57)
{
m=a[0]-48; //in ascii table, 49 stands of 1 and 57 stands for 9
}
else
{
m=a[0]-64; //in ascii table, 65 stands for 'A'
}
if (b[1]!='\0')
{
n=10;
}
else if (b[0]>=49 && b[0]<=57)
{
n=b[0]-48;
}
else
{
n=b[0]-64;
}
printf("%d", m n);
return 0;
}
It works but I think it is a little bit complicated. So I want to ask if there is any way to optimize the detection.
And how to deal with large input number.
Any help would be appreciated.
CodePudding user response:
You can use stroll
function to convert string to long long
. It looks much cleaner, and this program can deal from -9223372036854775808
to 9223372036854775807
as output.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char string_num1[20], string_num2[20];
scanf("%s%s", string_num1, string_num2);
long long num1 = strtoll(string_num1, NULL, 10);
long long num2 = strtoll(string_num2, NULL, 10);
long long num3 = num1 num2;
printf("%lld", num3);
return 0;
}