简体   繁体   中英

adding/subtracting floats/ints linux C

(can skip this part just an explanation of the code below. my problems are under the code block.)

hi. i'm trying to algro for throttling loop cycles based on how much bandwidth the linux computer is using. i'm reading /proc/net/dev once a second and keeping track of the bytes transmitted in 2 variables. one is the last time it was checked the other is the recent time. from there subtracts the recent one from the last one to calculate how many bytes has been sent in 1 second.

from there i have the variables max_throttle, throttle, max_speed, and sleepp.

the idea is to increase or decrease sleepp depending on bandwidth being used. the less bandwidth the lower the delay and the higher the longer.

i am currently having to problems dealing with floats and ints. if i set all my variables to ints max_throttle becomes 0 always no matter what i set the others to and even if i initialize them.

also even though my if statement says "if sleepp is less then 0 return it to 0" it keeps going deeper and deeper into the negatives then levels out at aroung -540 with 0 bandwidth being used.

and the if(ii & 0x40) is for speed and usage control. in my application there will be no 1 second sleep so this code allows me to limit the sleepp from changing about once every 20-30 iterations. although im also having a problem with it where after the 2X iterations when it does trigger it continues to trigger every iteration after instead of only being true once and then being true again after 20-30 more iterations.

edit:: simpler test cast for my variable problem.

#include <stdio.h>

int main()
{
int max_t, max_s, throttle;

      max_s = 400;
      throttle = 90;
      max_t = max_s * (throttle / 100);
      printf("max throttle:%d\n", max_t);


return 0;
}

In C, operator / is an integer division when used with integers only. Therefore, 90/100 = 0. In order to do floating-point division with integers, first convert them to floats (or double or other fp types).

max_t = max_s * (int)(((float)throttle / 100.0)+0.5);

The +0.5 is rounding before converting to int. You might want to consider some standard flooring functions, I don't know your use case.

Also note that the 100.0 is a float literal, whereas 100 would be an intger literal. So, although they seem identical, they are not.

As kralyk pointed out, C's integer division of 90/100 is 0 . But rather than using floats you can work with ints… Just do the division after the multiplication (note the omission of parentheses):

max_t = max_s * throttle / 100;

This gives you the general idea. For example if you want the kind of rounding kralyk mentions, add 50 before doing the division:

max_t = (max_s * throttle + 50) / 100;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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