浮点数转换为整数四舍五入_定义宏以将浮点值四舍五入为C中最接近的整数

浮点数转换为整数四舍五入

Given a float value and we have to round the value to the nearest integer with the help of Macro in C language.

给定一个浮点值,我们必须借助C语言中的Macro将其舍入到最接近的整数。

Macro Definition:

宏定义:

    #define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

Example:

例:

    Input:
    float val1=10.00f;
    float val2=10.23f;
    float val3=10.50f;
    float val4=10.65f;

    Output:
    After round val1=10
    After round val2=10
    After round val3=11
    After round val4=11

Program:

程序:

#include <stdio.h>

//Macro
#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

//Main code 
int main(void)
{
	float val1=10.00f;
	float val2=10.23f;
	float val3=10.50f;
	float val4=10.65f;

	printf("After round val1=%d\n",round(val1));
	printf("After round val2=%d\n",round(val2));
	printf("After round val3=%d\n",round(val3));
	printf("After round val4=%d\n",round(val4));

	return 0;
}

Output

输出量

After round val1=10
After round val2=10
After round val3=11
After round val4=11 


翻译自: https://www.includehelp.com/c-programs/define-a-macro-to-round-a-float-value-to-nearest-integer-in-c.aspx

浮点数转换为整数四舍五入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值