c/c++ 浮点型处理
#include <stdio.h> #include <iostream> #include <string> #include <string.h> #include <sstream> #include <iomanip> using namespace std; double round(double in, unsigned short decimal_presition) { int n_i = in; double small = (double)(in - n_i + (double)(5*pow(10, -decimal_presition - 1)); int n_f = small*(double)(pow(10, decimal_presition)); return n_i + (double)n_f/pow(10, decimal_presition); } double round_price(double price, int dotnum) { double out_price = 0.0; char buf[10]; memset(buf, 0, 0); std::string str("%."); sprintf(buf, "%d", dotnum); str += buf; str += "lf"; memset(buf, 0, 0); double cal_price = price + 0.0000001; sprintf(buf, str.c_str(), cal_price); cout << buf << endl; sscanf(buf, "%lf", &out_price); return out_price; } int main() { double dd = 5.6666666666; double two = round_price(dd, 2); cout << two << endl; stringstream stream; stream <<setiosflags(ios::fixed); stream.precision(2); stream << 5.665111; double one; stream >> one; cout << one << endl; return 0; }