我正在撰寫一個程式來計算 2 個變數的總和。其中一個是從 1 到 10 的數字,另一個是字母表中的一個字母(大寫),其值與其順序相對應。輸入可以是數字、字母或兩者。
例如:
輸入
10 7
C 8
E D
9 F
輸出
17
11
9
15
這是我的代碼(這個問題應該發布在 codereview 上,但由于某種原因,我無法在 codereview 上正確格式化代碼。請原諒我)。
#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;
}
它有效,但我認為它有點復雜。所以想問一下有沒有什么方法可以優化檢測。
以及如何處理大量輸入。
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
您可以使用stroll函式將字串轉換為long long. 看起來干凈多了,這個程式可以處理 from-9223372036854775808到9223372036854775807作為輸出。
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336491.html
