输入一个浮点小数, 将其按4舍5入转换成整数, 并显示

来源:互联网 发布:下载民间小调软件 编辑:程序博客网 时间:2024/05/16 00:41

刷了这道题, 感觉只有自己上机查资料才能作出来,  modf 头一次用, 原来还有这么个函数.

如果自己模拟modf, 只能用 float * 10 后,再mod 10来判断第一个小数位是否需要符合5入的条件.

用 modf 来做,逻辑清晰简洁.

// testvc6.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>#include <math.h>void fnTest();int float2int(float fIn);int main(int argc, char* argv[]){fnTest();getchar();return 0;}void fnTest(){/**输入一个浮点小数, 将其按4舍5入转换成整数, 并显示之.*/int iOut = 0;float fIn = 0.0f;printf("please input a float :");scanf("%f", &fIn);/** test case : fIn = 9.12, iOut = 9fIn = 9.54, iOut = 9*/// iOut = (int)fIn;// iOut = (int)(fIn + 0.50f);// iOut = (int)(9.60f); ///< 9.6f 强转成int, 也是9iOut = float2int(fIn); ///< 9.6f to 10 and -9.6f to -10printf("[%f] convert to [%d]\r\n", fIn, iOut);}int float2int(float fIn){double f_mod = .0f; ///< 小数部分double f_int = .0f; ///< 整数部分/** test casefIn = -9.4, returrn -9fIn = -9.6, returrn -10fIn = 9.4, returrn 9fIn = 9.6, returrn 10*/f_mod = modf(fIn, &f_int);if (fIn >= .0f){/// 正浮点数if (f_mod >= 0.5f){f_int += 1; ///< 9.6f to 10}}else{/// 负浮点数if (f_mod < -0.5f){f_int -= 1; ///< -9.6 to -10}}return (int)f_int;}

<2015-1019>

如果不用modf, 直接用 +0.5f 或 -0.5f 也可以将float 转成 int. 这样还简单一些.

不过modf 可以方便的分离float的整数部分和小数部分,在别的场合还是挺有用的.

// testvc6.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stdio.h>#include <math.h>void fnTest();void clear_input_buffer();int float2int(float fIn);int main(int argc, char* argv[]){fnTest();printf("END, press any key to quit\n");getchar();return 0;}void fnTest(){/**输入一个浮点小数, 将其按4舍5入转换成整数, 并显示之.*/int iOut = 0;float fIn = 0.0f;printf("please input a float :");scanf("%f", &fIn);clear_input_buffer();/** test case : fIn = 9.12, iOut = 9fIn = 9.54, iOut = 9*/// iOut = (int)fIn;// iOut = (int)(fIn + 0.50f);// iOut = (int)(9.60f); ///< 9.6f 强转成int, 也是9iOut = float2int(fIn); ///< 9.6f to 10 and -9.6f to -10printf("[%f] convert to [%d]\r\n", fIn, iOut);}int float2int(float fIn){double f_int = .0f; ///< 整数部分/** test casefIn = -9.4, returrn -9fIn = -9.6, returrn -10fIn = 9.4, returrn 9fIn = 9.6, returrn 10*//// 正浮点数 和 负浮点数 需要加的0.5f 方向不同 f_int = fIn + ((fIn >= .0f) ? 0.50f : (- 0.50f));return (int)f_int;}void clear_input_buffer(){char ch = '\0';/// scanf 的回车 0x0a, 留在了buffer里面, 用getchar()还能读的到, /// clear input bufferdo{ch = getchar();} while ((ch != EOF) && (ch != '\n'));}


0 0
原创粉丝点击