-1

i'm trying to calculate the px for different screen sizes. Now i have the problem that on my screen (1080x1920) the formular width/1080*1080 = 1080 but for another screen with width = 240 the formular has the result 0. can someone explain me why this happens? Do i have to choose another type for my values? i tried double, float and int. Everytime the result for 240*1080/1080 is 0.

Thanks.

user2798381
  • 21
  • 1
  • 6

6 Answers6

1

you are probably using integer division.

try adding .0 onto one of the values .

e.g.

240.0 / 1080.0 * 1080.0

This tells it to use double division. as a double is in the equation

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
0

You work with integers, so result is integer too. 240 / 1080 = 0, cause 0.xxx is not an integer. You should write next:

float smthng = width / 1080f * 1080f

it will return correct result for you.

Orest Savchak
  • 4,529
  • 1
  • 18
  • 27
0

I think of two options:

1) your value is rounded off

int 1080 divided by int 1080 gives 1

int 240 divided by int 1080 gives 0

2) the other screen does not support the function you use to get the width and some how you get zero.

It would help if you post the lines of code that you use to get the value, and to do the calculation.

JOG
  • 5,590
  • 7
  • 34
  • 54
0

Try this 1.0 * 240/1080*1080

You need to operate on floating-point type

Dominik Suszczewicz
  • 1,469
  • 2
  • 16
  • 23
0

Which language are you using? If you use:

int width = 1024;
float ratio = width / 1080 * 1080;

ratio will be = 0.0 (integer division of width by 1080, result is 0)

Try to use:

float ratio= (width/1080.0)*1080.0

The other point is: why are you try to calculate (A/B)*B? it's always A!

Mouze
  • 706
  • 5
  • 10
0

No matter what type you choose for the result, the operands you are providing are integers. Only the calculated result gets promoted from an int to a float - by which time it is already 0 (because 240/1080 is 0 in integer arithmetic). Note that the divide happens before the multiply because the operator precedence of / and * is equal, so the expression just gets evaluated from L to R.

If you want to use floating point, then provide floating point inputs with

float result = 240.0 / 1080.0 * 1080.0

The simplest solution is to keep using integer arithmetic and run the calculation in a different order, as

int result = (240 * 1080)/1080.
Airsource Ltd
  • 32,379
  • 13
  • 71
  • 75