繁体   English   中英

如何使是否浮动?

[英]How to make an if for being float or not?

我想知道是否可以为下一个示例创建if循环:

a=3;
b=2;
double c=a/b;
// if c is float cout<<"c is float";
// if c is int cout << "c is int";

我真的不知道如何将最后两行写为c ++代码..有人可以帮助吗?

我敢肯定,您说错了这个问题。 c的类型( intfloat或其他)由其声明确定,而不是由存储在其中的任何值决定。 鉴于:

double c;
c = 4;

int4int隐式转换为double ,因此c值为4.0 它仍然是double 类型的

我认为您要尝试确定c的当前值是否为整数。 如果其值不太大,则可以执行以下操作:

if (c == (int)c) {
    std::cout << "The value of C is a whole number\n";
}
else {
    std::cout << "The value of c contains a fractional part\n";
}

(int)c转换的值cint ,截断任何小数部分。 如果那不改变值,则没有小数部分。

要允许任意值,可以使用floor函数:

#include <cmath>

if (c == floor(c)) {
    std::cout << "The value of C is a whole number\n";
}
else {
    std::cout << "The value of c contains a fractional part\n";
}

typeid为您提供标识符的类型,但我不确定您要获得什么。 如果将c定义为浮点数,则无论a是否可被b整除,它都将是浮点数。

可能您需要的是if (a%b == 0) ,它与c的类型无关。 如果ab是整数,这将起作用。

如果只有浮点数c并要检查其小数部分是否为零,请使用floor()参见Keith Thompson的答案,但要注意浮点精度问题。

无论如何,这是使用typeid的价值的方法:

#include <iostream>
#include <typeinfo>
using namespace std;

int main() 
{
    int n;
    if (typeid(n) == typeid(int))
        cout << "n is an integer.\n";
}

如果您想知道除法是否得出整数,可以直接检查余数。 这比处理浮点更为直接。

if (a % b != 0) cout << "c is float";
if (a % b == 0) cout << "c is int";

当然,这仅在ab为整数时才有效。 如果不是,则可以使用modf查看结果的小数部分为零。

double dummy;
if (modf(c, &dummy) == 0.0) cout << "c is int";
#include<iostream>
using namespace std;
int main(){

    int a=3;
    int b=2;

    if((a % b != 0)
    {
        cout<<"float";
    }

    return 0;
}

暂无
暂无

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

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