Computer Question (intermediate)-output the frequency of occurrence of the specified symbol in decimal form (Java)
The questions are as follows:
The Code is as follows:
Package huawei; import java. math. bigDecimal; public final class Demo {/** function: count the frequency of occurrence of a specified character in the input benchmark string. The string only contains uppercase and lowercase letters, spaces, commas (,), and periods. after the decimal point, two valid digits are retained. The third digit is rounded to the nearest digit. ** enter: string pString input benchmark String char c specified character ** return: output frequency of the specified character */public static float getRateFromString (String pString, char c) {int num = 0; char pChar [] = pString. toCharArray (); for (int I = 0; I <pChar. length; I ++) {if (pChar [I] = c) {num ++ ;}} BigDecimal B = new BigDecimal (float) num/pChar. length); float f1 = (float) B. setScale (2, BigDecimal. ROUND_HALF_UP ). doubleValue (); // retain two decimal places return f1 ;}}
Note that the Division should be forcibly converted to float first, otherwise the precision may be lost, which is incorrect. In addition, there are many ways to retain two decimal places.