(原創) 如何抓出小数部份第n位数字? (C/C++)
C/C++的Library似乎都没这个功能,我就自己写了一个小Function。
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GetDigitFromDouble.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to get specified floating point number from double
7Release : 11/26/2006
8*/
9
10#include <iostream>
11
12int getDigitFromDouble(double, int);
13
14int main() {
15 double f = 6.532;
16 int i = getDigitFromDouble(f,2);
17 std::cout << i << std::endl;
18
19 return 0;
20}
21
22int getDigitFromDouble(double d, int n) {
23 int t = 1;
24 for(int j = 0; j != n-1; ++j) {
25 t *= 10;
26 }
27
28 d = d * t;
29 int i = (int)d;
30
31 return (int)((double)(d-i)*10);
32}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GetDigitFromDouble.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to get specified floating point number from double
7Release : 11/26/2006
8*/
9
10#include <iostream>
11
12int getDigitFromDouble(double, int);
13
14int main() {
15 double f = 6.532;
16 int i = getDigitFromDouble(f,2);
17 std::cout << i << std::endl;
18
19 return 0;
20}
21
22int getDigitFromDouble(double d, int n) {
23 int t = 1;
24 for(int j = 0; j != n-1; ++j) {
25 t *= 10;
26 }
27
28 d = d * t;
29 int i = (int)d;
30
31 return (int)((double)(d-i)*10);
32}