Anatamize
Anatamize

Reputation: 27

Minimum answer c++

I'm beginner, and trying to understand how to calculate a math function, and if the answer is below 0, set it to 0. I know I could use an if statement, but it seems like bad practice and I can't find if there's a better way to do it. I ask this because in visual basic there were min functions, I am curious if there is in c++.

Here's an example

int a = 5;
int b = -6;
int answer = a + b; 
//Answer would be -1 at this point.
if(answer < 0){answer = 0;}

Let me know if there is an easier way to do with, perhaps with a minimum value function.

EDIT: Follow up, how would I do the max function with only 1 value? For example, If I wanted to compare ANSWER to 0, instead of a, b and 0?

Upvotes: 0

Views: 298

Answers (4)

Zac Howland
Zac Howland

Reputation: 15872

You can do this a ton of different ways. Here are a couple of the more straight-forward ways:

int answer1 = std::max(a + b, 0);
int answer2 = (a + b) < 0 ? 0 : (a + b);
int answer3 = (::abs(b) >= a && b < 0) ? 0 : (a + b);

Note that you do not actually want to use std::min for your problem, but rather std::max.

To answer your follow up question, it would look like this:

int answer4 = std::max(a, 0);
int answer5 = (a > 0) ? a : 0;

Upvotes: 11

BBekyarov
BBekyarov

Reputation: 187

int a = 5;
int b = -6;
int answer;

You can go like this int answer = (a + b) < 0 > 0 : (a + b);

or you can use its equavalent

if( (a + b) < 0 )
   answer = 0;
else 
   answer = a + b;

Upvotes: 0

mcsilvio
mcsilvio

Reputation: 1098

That's pretty minimal. There's always "inline ifs":

int answer = a + b;
answer = answer < 0 ? 0 : answer;

I think you're code is better and more readible.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

An equivalent declaration is

int a = 5;
int b = -6;
int answer = std::max( a + b, 0 ); 

Upvotes: 11

Related Questions