有人可以解释为什么该程序可以计算小数点后的位数吗?

时间:2019-03-31 01:10:50

标签: c++

显然,该程序可以计算小数点后的位数。虽然可以,但是我很难理解。

布尔在这里到底做了什么?而if(ch =='。')f = true会怎样?在这里实现?

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    char ch;
    bool f=false;
    int num=0;

    while((ch=getchar())!='\n')
    {
        if(f)
            if(ch>='0' && ch<='9')
                num++;
            else
                break;
        if(ch=='.')
            f=true;
    }
    if(num>0)
        cout<<num<<endl;
    else
        cout<<"false"<<endl;
    return 0;
}

它可以完美地给出结果。只是好奇为什么会起作用。

4 个答案:

答案 0 :(得分:2)

我不怪你困惑。它表明了好的变量名的重要性。 UnregisterReceiver();跟踪我们是否看过f。应该将其命名为更具描述性的名称,例如'.'

haveSeenDecimalPoint

开头为false,表示我们还没有看到bool haveSeenDecimalPoint=false; while((ch=getchar())!='\n') { if(haveSeenDecimalPoint) if(ch>='0' && ch<='9') num++; else break; if(ch=='.') haveSeenDecimalPoint=true; } 。第一个.语句始终为假。当我们看到if时,第二条.语句会将标志设置为true。之后,任何其他字符将触发内部的if / if测试。小数点后的任何数字都会触发else,一旦我们看到一个非数字,我们就会num++完全退出循环。

答案 1 :(得分:1)

{fbool类型的变量(不是函数,尽管它没有非常描述性的名称),在这种情况下,它标记了已经遇到.个字符。它从false开始,并在读取true字符后切换到.。这就是if (ch == '.') f = true的目的。

一旦找到.字符,它将开始对数字进行计数。这是这些行的用途:

if ('0' <= ch && ch <= '9') num++; // Count a digit character
else break;                        // If not a digit, break the loop

中断循环后,其余代码仅打印找到的位数。

答案 2 :(得分:0)

该答案应该是注释,但注释不允许呈现更复杂的代码...

John Kugelman已经给出了一个适当的answer,但是代码的结构仍然可以更好:

if(haveSeenDecimalPoint)
// while braces are optional in given case, they still better are placed
// as the following code is pretty complex; you gain better overview
{
    if('0' <= ch && ch <= '9') // optional; ressembles closer mathematical
                               // expression 0 <= ch <= 9
                               // (which cannot be written that way in C++!)
        num++;
    else
        break;
}
// if decimal point HAS been found already, no need to check any further
// so place the else to avoid unnecessary checks (if another period occures, 
// it's already covered by breaking on ch < '0' || ch >= '9')
else if(ch == '.')
{ // due to the newly introduced else: recommendation: if one branch needs 
  // braces, place on all of them – some coding conventions even mandate
  // ALWAYS placing braces
    haveSeenDecimalPoint = true;
}

不带注释的代码:

if(haveSeenDecimalPoint)
{
    if('0' <= ch && ch <= '9')
        num++;
    else
        break;
}
else if(ch == '.')
{
    haveSeenDecimalPoint = true;
}

注意额外放置的空间,它们也提高了可读性。

答案 3 :(得分:0)

该循环正在执行两种不同的操作,并使用f来跟踪其正在执行的操作。这通常令人困惑,并且代码可能应该写成两个单独的循环:

// skip until the decimal point
while ((ch = getchar()) != '\n' && ch != '.')
    ; // nothing to do here

// check that we haven't hit the end of the input
if (ch != '\n')
    // count digit characters
    while ((ch = getchar()) >= '0' && ch <= '9')
        ++num;

请注意,在最后一个循环中,没有'\n'的显式检查;不需要这样做,因为'\n'不在'0''9'之间,因此获取'\n'将结束循环。

相关问题