你怎么知道用户输入中有多少小数位?

时间:2014-04-16 22:11:19

标签: c rounding

我正在尝试编写一个程序,该程序需要一个数字和所需的小数位数,然后通过比较该数字与该数字+1的距离来适当地舍入该数字。

int main() {
double tester;
int numberOfDecimals;

printf("Enter a number to be rounded: ");
scanf("%lf",&tester);
printf("%d rounded to how many decimal places? ",tester);
scanf("%d", &numberOfDecimals);

在我要求他们想要数字四舍五入的小数位数后,如何查看他们输入的数字中有多少小数位?

1 个答案:

答案 0 :(得分:0)

int main() {
double tester;
int numberOfDecimals;
char strBuf[255+1];
char *decimalPoint;
int decimalPlacesOfInput = 0;

printf("Enter a number to be rounded: ");
fgets(strBuf, sizeof(strBuf), stdin);

decimalPoint=strchr(strBuf, '.');
if(decimalPoint)
   {
   ++decimalPoint;
   while(isdigit(*decimalPoint))
      {
      ++decimalPlacesOfInput;
      ++decimalPoint;
      } 
   }

printf("Number entered with %d decimal places.\n", decimalPlacesOfInput);

tester=atof(strBuf);
printf("%d rounded to how many decimal places? ",tester);
scanf("%d", &numberOfDecimals);
...