I
I
Ingvar Von Bjork2018-05-26 20:15:40
C++ / C#
Ingvar Von Bjork, 2018-05-26 20:15:40

Dividing the smaller by the larger returns zero. How to fix?

For a long time, of course, I haven’t written in C #, but I haven’t met this one yet. Actually, let's say, if 1 is divided by 7, 0 will be returned as an answer.
For example: Am I doing something wrong, is it a bug in VS, or has the division rules changed?
Console.WriteLine((1 / 7).ToString());

Answer the question

In order to leave comments, you need to log in

3 answer(s)
#
#, 2018-05-26
@mindtester

no and no... almost all the words. almost correct ...
but the bottom line is that if both operands are int then the result will be int ...
start with this
or
or
or
or
or
to be sure compare with
... consider why in the last example, the conversion to "floating point" is late ... and there will be a complete understanding , good luck ..
ps
... you can just check everything here - https://dotnetfiddle.net/
... and here I'm sorry)))... in C # it has always been like this (more precisely, in all strongly typed PLs)

V
Vyacheslav Ryzhkov, 2018-05-26
@rugrisser

Try to deduce this expression into a variable with the type of real numbers (float/double/decimal), then also deduce (with .ToString();). Outputs 0 because it treats them as int(integer) and therefore performs integer division. You can also try to replace, for example, 1 with 1.0, so that the compiler perceives it as a real number

I
Ingvar Von Björk, 2018-05-26
@DeboshiR

However, I found a very suitable answer myself:Console.WriteLine(((double) 1 / 7).ToString());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question