习题8-1 拆分实数的整数与小数部分(15 分)

习题8-1 拆分实数的整数与小数部分(15 分)

本题要求实现一个拆分实数的整数与小数部分的简单函数。

函数接口定义:

1
void splitfloat( float x, int *intpart, float *fracpart );

其中x是被拆分的实数(0≤x<10000),*intpart*fracpart分别是将实数x拆分出来的整数部分与小数部分。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

void splitfloat( float x, int *intpart, float *fracpart );

int main()
{
float x, fracpart;
int intpart;

scanf("%f", &x);
splitfloat(x, &intpart, &fracpart);
printf("The integer part is %d\n", intpart);
printf("The fractional part is %g\n", fracpart);

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

1
2.718

输出样例:

1
2
The integer part is 2
The fractional part is 0.718
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>

void splitfloat( float x, int *intpart, float *fracpart );

int main()
{
float x, fracpart;
int intpart;

scanf("%f", &x);
splitfloat(x, &intpart, &fracpart);
printf("The integer part is %d\n", intpart);
printf("The fractional part is %g\n", fracpart);

return 0;
}

void splitfloat(float x, int *intpart, float *fracpart) {

if(x<0) x=-x;

*intpart=(int)x;

*fracpart=x-*intpart;

}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×