題目鏈接:uva 1530 - Floating Point Numbers
題目大意:給出一個16位的二進制數,用來表示一個浮點數,第一位為符號,1~7位表示一個十進制的數s,e=63-s;剩下的8位為小數部分,默認整數部分為1,得到f,然後最後a=f*2^e,要求用科學計數法輸出a。
解題思路:模擬就好了,注意0的情況特殊處理,以及科學計數法的整數部分不能為0.
#include#include #include #include const int N = 20; const double eps = 1e-6; char s[N]; int main () { printf("Program 6 by team X\n"); while (scanf("%s", s) == 1) { if (strcmp(s+1, "000000000000000") == 0) { printf(" 0.000000e+000\n"); continue; } int sign = (s[0] == '1' ? 1 : 0); int e = 0; for (int i = 1; i <= 7; i++) { if (s[i] == '1') e += (1<<(7-i)); } double a = 1; for (int i = 8; i < 16; i++) { if (s[i] == '1') a += pow(2, 7-i);; } a *= pow(2, e-63); e = log10(a); a /= pow(10, e); if (a < 1) { a *= 10; e--; } printf("%c", sign ? '-' : ' '); printf("%.6lfe", a); printf("%c", e < 0 ? '-' : '+'); printf("%03d\n", abs(e)); } printf("End of program 6 by team X\n"); return 0; }