简体   繁体   English

c++ - 如何在c ++中获得除法以产生浮点值

[英]How to get division to produce float value in c++

I was looking back into a calculator I made a while back and noticed that the division did not work, calculating expressions such as 3/4 as 0. I tried to fix it by converting from ints to floats, something which I did not know at the time of making the calculator.我正在回顾我不久前制作的计算器,注意到除法不起作用,将 3/4 等表达式计算为 0。我试图通过从整数转换为浮点数来修复它,这是我不知道的制作计算器的时间。 For some reason, however, it does not work.但是,由于某种原因,它不起作用。 Am I messing up the syntax?我搞砸了语法吗?

Code:代码:

int divide(int num1, int num2) {
    float quot;
    quot = (float) num1 / num2;
    return quot;
}

Whenever I call my divide function, it gives me integer answers.每当我调用我的除法函数时,它都会给我整数答案。 I want fractional (decimal) answers.我想要分数(十进制)答案。

只需将 int 更改为 float 在您的函数返回类型中

This was dumb, just figured it out.这很愚蠢,只是想通了。 I needed to define my division function as float divide .我需要将我的除法函数定义为float divide

float divide(int num1, int num2) {
    float quot;
    quot = (float) num1 / num2;
    return quot;
}

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

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