当前位置:网站首页>实数取整写入文件(C语言文件篇)
实数取整写入文件(C语言文件篇)
2022-08-03 12:28:00 【一沐四季】
题目要求:文件f1.txt中有若干个实数,请分别读出,将每个实数按四舍五入取整后存入存入文件f2.txt中。试编写相应程序。
思路:
- 打开文件f1,
- 读入实数,
- 将实数的整数部分和小数部分拆开,
- 小数部分与0.5相比较,
- 整数部分作出对应调整并写入文件f2。
运行后文件内容:
| ![]() |
| f1.txt(自行输入) | f2.txt(运行后系统生成) |
源程序:
#include<stdio.h>
#include<stdlib.h>
void splitfloat(double x,int *intpart,double *fracpart)
{
*intpart=(int)x;//强制转换为整型
*fracpart=x-*intpart;//直接减去整数部分可得小数部分
}
int main(void)
{
FILE *fp1,*fp2;
int intpart;//x=345.89,小数部分为0.890015
double z,fracpart,a;//x=123.456,小数部分会输出为0.456001
if((fp1=fopen("f1.txt","r"))==NULL){
printf("文件f1打开失败!");
exit(0);
}
if((fp2=fopen("f2.txt","w"))==NULL){
printf("文件f2打开失败!");
exit(0);
}
while(!feof(fp1)){
fscanf(fp1,"%lf",&z);//读取
if(z!=EOF){
splitfloat(z,&intpart,&fracpart);//拆分整数和小数部分
// printf("整数部分:%d\n小数部分:%lf\n",intpart,fracpart);//帮助检验
if(fracpart>=0.5){//小数部分 四舍五入
intpart=intpart+1;
// printf("整数部分:%d\n小数部分:%lf\n",intpart,fracpart);//帮助检验
}
fprintf(fp2,"%d\n",intpart);
}
}
return 0;
}其中拆分实数的整数与小数部分原题目:
要求自定义一个函数 void splitfloat ( float x , int * intpart , float * fracpart ),其中 x 是被拆分的实数,* intpart 和* fracpart 分别是将实数 x 拆分出来的整数部分与小数部分。编写主函数,并在其中调用函数 splitfloat ()。
源程序:
#include<stdio.h>//习题8.1 拆分实数的整数与小数部分
void splitfloat(float x,int *intpart,float *fracpart)
{
*intpart=(int)x;//强制转换为整型
*fracpart=x-*intpart;//直接减去整数部分可得小数部分
}
main(void)
{
float x,fracpart;//x=123.456,小数部分会输出为0.456001
int intpart;//x=345.89,小数部分为0.890015
printf("Enter x:");
scanf("%f",&x);
splitfloat(x,&intpart,&fracpart);
printf("整数部分:%d\n小数部分:%lf",intpart,fracpart);
return 0;
}
边栏推荐
- 深入理解MySQL事务MVCC的核心概念以及底层原理
- Mysql重启后innodb和myisam插入的主键id变化总结
- From scratch Blazor Server (6) - authentication based on strategy
- shell编程条件语句
- R语言ggplot2可视化:使用patchwork包的plot_layout函数将多个可视化图像组合起来,ncol参数指定行的个数、byrow参数指定按照行顺序排布图
- 使用 %Status 值
- 免费的网络传真平台_发传真不显示发送号码
- Kubernetes 网络入门
- Key points for account opening of futures companies
- 浅谈程序员的职业操守
猜你喜欢
随机推荐
flink流批一体有啥条件,数据源是从mysql批量分片读取,为啥设置成批量模式就不行
Explain the virtual machine in detail!JD.com produced HotSpot VM source code analysis notes (with complete source code)
Apache APISIX 2.15 版本发布,为插件增加更多灵活性
Feature Engineering Study Notes
苹果发布 AI 生成模型 GAUDI,文字生成 3D 场景
YOLOv5 training data prompts No labels found, with_suffix is used, WARNING: Ignoring corrupted image and/or label appears during yolov5 training
Byte's favorite puzzle questions, how many do you know?
-树的高度-
基于php校园医院门诊管理系统获取(php毕业设计)
AMS simulation
Oracle安装完毕(系统盘),从系统盘转移到数据盘
AMS simulation
After completing the interview and clearance collection of Alibaba, I successfully won the 15th Offer this year
7月份最后一篇博客
__unaligned修饰指针
随机森林项目实战---气温预测
安全自定义 Web 应用程序登录
安防监控必备的基础知识「建议收藏」
Blazor Server(6) from scratch--policy-based permission verification
为冲销量下探中低端市场,蔚来新品牌产品定价低至10万?











