close
題目概要:
輸入2個字串,A=1,B=2,C=3...Z=26(不分大小寫),計算字母總和。假如總和不是個位數,則總和裡面的數字相加,直到變成個位數為止。Ex saima(19+1+9+13+1)=43 → 4+3=7。2個字串都算出來後,由數字大的作為分母,數字小的作為分子,計算分比。
解題方向:
把接收的字串統一換成大寫(or小寫),以方便加總。依題目意思讓總和變個位數。2個字串都算出總合後,再算出百分比。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class main{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
while(sc.hasNextLine()){ | |
//讀入字串,並統一變成小寫。再傳入自己定義的Method進行運算。 | |
double val1=change(sc.nextLine().toLowerCase()); | |
double val2=change(sc.nextLine().toLowerCase()); | |
//計算出百分比。最大值當分母,最小值當分子。 | |
if(Math.max(val1,val2)!=0)System.out.printf("%.2f %%",(Math.min(val1,val2)/Math.max(val1,val2))*100); //分母不為0。 | |
else System.out.print("-1.#J %"); // 當0.0/0.0時Java會輸出NaN。但題目則是會輸出-1.#J(如果使用C、C++則不需要定義這行)。 | |
System.out.println(""); | |
} | |
} | |
public static double change(String st){ | |
double val=0; | |
//計算總和。 | |
for(int i=0;i<st.length();i++){ | |
if(st.charAt(i)>=97 && st.charAt(i)<=122) val=val+st.charAt(i)-96; | |
} | |
//讓總和小於10。 | |
while((int)val>=10){ | |
val=(int)val/10+(int)val%10; | |
} | |
return val; | |
} | |
} |
文章標籤
全站熱搜