当前位置:网站首页>实数取整写入文件(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;
}
边栏推荐
猜你喜欢

4500 words sum up, a software test engineer need to master the skill books

链游NFT元宇宙游戏系统开发技术方案及源码

What knowledge points do you need to master to learn software testing?

业界新标杆!阿里开源自研高并发编程核心笔记(2022最新版)

YOLOv5 training data prompts No labels found, with_suffix is used, WARNING: Ignoring corrupted image and/or label appears during yolov5 training

Apache APISIX 2.15 版本发布,为插件增加更多灵活性

622. 设计循环队列

Unsupervised learning KMeans notes and examples

Feature dimensionality reduction study notes (pca and lda) (1)

setTimeout 、setInterval、requestAnimationFrame
随机推荐
Take you understand the principle of CDN technology
SQL分页查询_Sql根据某个字段分页
免费的网络传真平台_发传真不显示发送号码
bash if conditional judgment
Blazor Server(6) from scratch--policy-based permission verification
项目概述、推送和存储平台准备
PC client automation testing practice based on Sikuli GUI image recognition framework
Free Internet fax platform fax _ don't show number
什么是分布式锁?几种分布式锁分别是怎么实现的?
B站回应“HR 称核心用户都是 Loser”:该面试官去年底已被劝退,会吸取教训加强管理
pytorch+tensorboard使用方法
AMS simulation
使用工作队列管理器(三)
15. PARTITIONS「建议收藏」
PolarFormer: Multi-camera 3D Object Detection with Polar Transformers 论文笔记
深入理解MySQL事务MVCC的核心概念以及底层原理
海外代购系统/代购网站怎么搭建——源码解析
Using the Work Queue Manager (4)
Secure Custom Web Application Login
Random forest project combat - temperature prediction

