输入一个浮点数,要求把每一位数字分解并打印出来
不允许采用把整体扩大若干倍的方法
肯定两位小数么?或者不超过两位小数吧
采用c语言的库函数modf来实现此功能
#include <iostream>
#include <cmath>
#include <string.h>
#include <string>
using namespace std;
int main() {
double num;
cin >> num;
double int_part;
double frac_part = modf(num, &int_part);
string int_str = to_string((int)int_part);
for (char c : int_str) {
cout << c << " ";
}
cout << ". ";
int i = 0;
int n = 2;//小数点后n位
while (i < n) {
frac_part *= 10;
double int_part;
frac_part = modf(frac_part, &int_part);
cout << (int)int_part << " ";
i++;
}
cout<<endl;
return 0;
}
这样已经做到了将整数和小数部分给分离打印了
但是,测试可以看到,小数的最后一位出现了可能会存在的精度缺失。所以还需要用另外一个办法来处理
#include <iostream>
#include <cmath>
#include <string.h>
#include <string>
using namespace std;
//https://ask.csdn.net/questions/7901417
int main() {
double num;
cin >> num;
double int_part;
double frac_part = modf(num, &int_part);
cout << "int_part: "<< int_part <<" | frac_part: " <<frac_part << endl;
char str[10];
sprintf(str, "%.3f", frac_part); //将小数部分打印到字符串中
cout << "str: " << str << endl;
// 打印整数部分
string int_str = to_string((int)int_part);
for (char c : int_str) {
cout << c << " ";
}
cout << ". ";
// 打印小数部分
int n = 2;//小数点后n位
for(int i=0;i<n;i++)
{
// 因为打印到字符串中的数据包含了最开始的0.
// 前两个字符就是0. 应该从第三个字符开始打印
cout << str[2+i] << " ";
// frac_part *= 10;
// double int_part;
// frac_part = modf(frac_part, &int_part);
// cout << int_part << " ";
}
cout << endl;
return 0;
}
可以看到,问题已解决
如果对你有帮助,还请点个采纳,万分感谢!