English 中文(简体)
为什么结果输出是整数甚至结果被定义为浮点?
原标题:Why result output is integer even result is defined as float?
  • 时间:2011-02-14 00:05:56
  •  标签:
  • c++
#include<iostream>

using namespace std;

int main(int argc, char** argv){
        float result;
        result=(340/101);
        cout<<"Result="<<result;

}

在这段代码中,的结果是=3,我很好奇为什么会这样?这个原因的预防措施是什么?这可以看作是一个小问题,但它确实贬低了我在数据分析程序中的结果。

编辑:谢谢你的回答,我正在尝试下面的代码,它也给了我3,所以这就是为什么我现在很困惑,我很清楚了。

result=(float)(340/101);

谢谢大家

最佳回答

340是整数,101为整数,因此340/101执行整数除法。当除法结果被分配给结果时,除法结果被转换为浮点

您需要将一个强制转换为浮点类型才能执行浮点除法:

result = static_cast<float>(340)/101;

或者只使用浮动文字:

result = 340.0f/101;
问题回答

因为表达式(340/101)的求值与其周围的上下文无关int/int总是导致int。如果稍后将int存储在float变量中,则没有什么区别。

这是由于整数除法,因为除法运算中的两个操作数都是整数。将其中一个数字强制转换为浮点,或使用浮点语法:

result = (340.0 / 101.0)

在C++中,(340/101)被认为是孤立的。由于/的两个操作数都是ints,因此编译器生成整数除法的代码。然后,由于您将该结果重新分配给float,因此它会生成代码,将生成的int转换为浮点

要获得浮点除法,您需要确保(至少)/的一个操作数以float(或double)开头,例如:浮点结果=340.0f/101.0f





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?