woaigaocheng 2023-03-13 18:22 采纳率: 0%
浏览 264

输入一个浮点数,要求把每一位数字分解并打印出来

输入一个浮点数,要求把每一位数字分解并打印出来
不允许采用把整体扩大若干倍的方法

img

  • 写回答

4条回答 默认 最新

  • 慕雪华年 C/C++领域新星创作者 2023-03-13 19:12
    关注

    采用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;
    }
    

    这样已经做到了将整数和小数部分给分离打印了

    img

    img

    但是,测试可以看到,小数的最后一位出现了可能会存在的精度缺失。所以还需要用另外一个办法来处理

    #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;
    }
    

    可以看到,问题已解决

    img

    如果对你有帮助,还请点个采纳,万分感谢!

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 3月13日

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答