better way to do this?

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This is a simple issue, but the fix I used seems like a hack to me.

 

float foo=0.0;

 

(assign a value to foo)

 

if abs(10*foo >100)

 cntxcs = cntxcs+1;

 

Here's the deal. I want to know if abs( foo) is >1 0, but I finally looked close ennough to see that abs deals with ints -- explained my strange issue of short counts,

Multiplying by 10 gives me the int that I need, but I really don't like it.

 

Somebody please show me the simple and clear way to do this.

 

Thanks,

 

hj

 

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

ford2go wrote:

if abs(10*foo >100)

 cntxcs = cntxcs+1;

 

Please, make an effort to at least balance your braces. This is unreadable.

 

ford2go wrote:

Here's the deal. I want to know if abs( foo) is >1 0,

 

`1 0` is supposed to be `10`, right?

 

Then just do 

 

if (foo < -10 || foo > 10)
  ...

no need to involve `abs`.

 

Or you can simply do

 

if ((foo >= 0 ? foo : -foo) > 10)
  ...

just to see which version produces a better code.

 

ford2go wrote:
but I finally looked close ennough to see that abs deals with ints -- explained my strange issue of short counts,

 

This is not entirely accurate. It actually depends on the language. What language are you talking about: C or C++?

 

In C `abs` indeed deals with `int`. But C also has `fabs` and `fabsf` that work with `double` and `float` respectively. You can do

 

if (fabsf(foo) > 10)
  ...

 

but it might end up being less efficient than the previous variants.

 

In C++ `abs` is overloaded and can deal with all arithmetic types by itself.

 

ford2go wrote:
Multiplying by 10 gives me the int that I need, but I really don't like it.

 

Then don't.

 

Then again there is also an issue of your `foo` being a `float`. Why `float`? Does it have to be `float`? Floating-point types are quite "heavy", you know. Maybe you can use fixed-point format from the very beginning, i.e. use an integer variable that is already "multiplied by 10" internally? But there's no way to say say without knowing the context. 

 

Dessine-moi un mouton

Last Edited: Fri. May 31, 2019 - 06:04 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I agree with Andrey but just to point out that the math lib has fabs() should you ever need it.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks for the plethora of comments. I apologize for the poor post.  A coworker once referred to me as a dyslexic typist -- and it's pretty true.

 

foo ( not its real name :) ) pretty much has to be a float 

 

Thanks again,

 

hj

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

foo ( not its real name :) ) pretty much has to be a float 

That sounds suspicious---what makes you say that? 

When in the dark remember-the future looks brighter than ever.   I look forward to being able to predict the future!