简体   繁体   English

modf无法正常工作

[英]modf does not work properly

This code should display if first 3 digits of fractional part contains "9", but does not work. 如果小数部分的前3位数字包含“ 9”,则该代码应显示,但不起作用。 "mod" variable, surprisingly, is 0 for any number. 令人惊讶的是,“ mod”变量对于任何数字都是0。

int main( void )
{
    float number, dmod;
    int mod;
    double digit_1, digit_2, digit_3;
    double search=9;

    cout<<"Enter the number:";
    cin>>number;

    mod = modf(number, &dmod);
    digit_1 = mod /100 % 10;
    digit_2 = mod /10  % 10;
    digit_3 = mod /1   % 10;

    if( (digit_1 == search) || (digit_2 == search) || (digit_3 ==search) )
    {
        cout<<"mod contains 9"<<endl;
    }
    else
    {
        cout<<"mod does not contains 9"<<endl;
    }
 }

Your problem is that modf returns the fractional part , not an integer representing the fractional part. 您的问题是modf返回小数部分 ,而不是代表小数部分的整数。 The value returned is always less than one and then when assigned to an int it gets truncated down to 0. 返回的值始终小于1,然后将其分配给int时将其截断为0。

Maybe you wanted to multiply the return by 1000: mod = modf(number, &dmod) * 1000.0; 也许您想将收益乘以1000: mod = modf(number, &dmod) * 1000.0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM