【问题标题】:Having problems with rounding integers in C [closed]在 C 中舍入整数时遇到问题 [关闭]
【发布时间】:2021-09-13 02:44:19
【问题描述】:

我有一个练习可以告诉我这些:

功能
问题1
函数floor 可用于将数字四舍五入到特定的小数位。声明

y = floor( x * 10 + .5 ) / 10;

将 x 舍入到十分位(小数点右侧的第一个位置)。这 声明

y = floor( x * 100 + .5 ) / 100;

将 x 舍入到百分之一(小数点右侧的第二个位置) 点)。

编写一个程序,定义四个函数以各种方式对数字 x 进行四舍五入

一个。 roundToInteger( 数字 )
湾。 roundToTenths( 数字 )
C。 roundToHundreths( 数字 )
d。 roundToThousandths(数字)

对于读取的每个值,您的程序应打印原始值,数字四舍五入为 最接近的整数,数字四舍五入到最接近的十分之一,数字四舍五入到 最接近的百分之一,数字四舍五入到最接近的千分之一。

输入格式
输入行包含一个浮点数。

输出格式
打印原始值,数字四舍五入到最接近的整数,数字四舍五入 到最接近的十分之一,数字四舍五入到最接近的百分之一,数字 四舍五入到最接近的千分之一

例子:

输入
24567.8
输出
24567.8 24568 24570 24600

我的解决方案(这是错误的)是:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double roundToInteger(double number)
{
   double roundedNum;
   roundedNum = floor(number + .5);
   return roundedNum;
}

double roundToTenths(double number)
{
   double roundedNum;
   roundedNum = floor(number * 10.0 + .5) / 10.0;
   return roundedNum;
}

double roundToHundreths(double number)
{
   double roundedNum;
   roundedNum = floor(number * 100.0 + .5) / 100.0;
   return roundedNum;
}

double roundToThousandths(double number)
{
   double roundedNum;
   roundedNum = floor(number * 1000.0 + .5) / 1000.0;
   return roundedNum;
}

int main()
{
  double userInput = 0.0, userInput1 = 0.0, userInput2 = 0.0,userInput3 = 0.0, userInput4 = 0.0, originalVal = 0.0;

  printf("Enter a double value: ");
  scanf("%lf", &userInput);

  originalVal = userInput;

  userInput1 = roundToInteger(userInput);

  userInput2 = roundToTenths(userInput);
 
  userInput3 = roundToHundreths(userInput);
 
  userInput4 = roundToThousandths(userInput);
 
  printf("%lf %lf %lf %lf %lf", originalVal, userInput1,userInput2,userInput3, userInput4);
}

公式中我做错了什么?

【问题讨论】:

  • 示例输出与问题描述不符。那么哪个是正确的,问题描述还是示例?
  • 例如,您是四舍五入到最接近的百位还是百位?
  • 您似乎混淆了两种不同的练习。一个用于四舍五入到小数位,另一个用于四舍五入到 10 的幂。
  • floor(number * 100.0 + .5)/100.0 技巧会导致许多 FP 值的错误答案。为什么要使用floor(),因为round() 可用?

标签: c integer double rounding


【解决方案1】:

如果输入是 24567.8 并且预期输出是 24567.8 24568 24570 24600,请将您的公式更改为:

y = floor( x * 10...0 + .5 ) / 10...0;

收件人:

y = floor( x / 10...0 + .5 ) * 10...0;

换句话说,您正确地实现了所提供的公式。这里唯一的错误是公式对于四舍五入的十次方是错误的。这些是用于四舍五入的小数位。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多