计算浮点数字(hw)C [英] counting float digits (hw) C
本文介绍了计算浮点数字(hw)C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从 float
数字中计算数字并保留数字。
我可以将 scanf()
与%f
或%c一起使用
而不是%s
,我可以使用 getchar()
。
I need to count digits from a float
number and keep the number.
I can use scanf()
with %f
or %c
but not %s
, and I can use getchar()
.
我可以使用getchar,但我会丢失数字。
I can use getchar but I will loose the number.
推荐答案
为什么您会丢失用 getchar
来编号?
Why will you lose the number with getchar
?
- 使用getchar读取字符,直到按下空格/回车/输入结尾
- 将它们全部收集到一个字符串中
- 使用
strtod
来确保这是有效的浮点值 - 对字符串中的数字进行计数-在该点之前或之后,无论您需要什么。
- Read characters with getchar until you hit whitespace/enter/end of input
- Collect them all into a single string
- Use
strtod
to make sure it's a valid floating point value - Count digits in the string - either before, or after the point, whatever you need.
如果您仅限于 getchar
:
- 使用
getchar
- 逐一读取字符,保持数字所在的状态:小数点前,小数点前点,或之后
- 只要是有效的浮点数(即1或m矿石位数,然后可选地是一个小数点,其后有1个或多个数字)
- 通过移动10的幂来将数字收集为浮点数(即小数点前乘以10.0并添加新数字,小数点后除以10的乘幂并加)。
- Read chars one by one with
getchar
- Keep a state of where you are in the number: before decimal point, at decimal point, or after
- Keep counting the digits as long as it's a valid floating point number (i.e. 1 or more digits, then optionally a decimal point with 1 or more digits after it)
- Collect the digits into a floating point number by shifting powers of 10 (i.e. before decimal point multiply by 10.0 and add new number, after decimal point divide by a growing power of 10 and add).
这篇关于计算浮点数字(hw)C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文