Salutations! I am experimenting with the floor and ceil for a code. Here is the code below. So, it appears the if...else statement I put in there do not work. I was wondering where I would put the code, in setup, or loop and if I declared the variables properly? Thank you in advance!
int floatValue;
int result;
int num;
void setup() {
Serial.begin(9600);
Serial.println( floor(1) );
Serial.println( floor(1.1) );
Serial.println( floor(0) );
Serial.println( floor(.1) );
Serial.println( ceil(1) );
Serial.println( ceil(1.1) );
Serial.println( ceil(0) );
Serial.println( ceil(.1) );{
if (floatValue > 0.0)
result = floor(floatValue + 0.5);
else
result = ceil(num - 0.5);
}
}
void loop() {
}/code]
You never change the value of floatValue so it will always be it's default initialization value of 0.0. Thus the if statement will never evaluate as true.
The if statement also doesn't have any output so you'll never be able to observe what it is doing.
I recommend always using braces with if/else if/else. Although it's not absolutely necessary in this case, it's just too easy to end up with bugs when you skip the braces. It really doesn't take much extra effort or space to use them. You also have an unnecessary extra set of braces starting on line 16. That just makes the code harder to understand.
So would the code be something like int floatValue = (x, condition)? And would it make more sense switch it from a global variable to a static variable? Thank you for bearing with me!
Yog1Girl:
So would the code be something like int floatValue = (x, condition)?
I don't think so. If that is actually valid code, it almost certainly doesn't do what you intend it to do. You need to explain what you are trying to accomplish. Your current code's if statement is technically correct but it has absolutely no purpose so it's hard for us to know how to give you advice to fix it.
Yog1Girl:
And would it make more sense switch it from a global variable to a static variable?
Again, I can't answer that without knowing what you're trying to accomplish. In your current code, there is no benefit to using globals or static because you only have code in a single function so you could just make all variables local. The benefit of static variables vs. global variables is their scope is more limited, which makes name collisions less likely in complex programs. At the stage you're at now, I would not think at all about static. Just use regular global and local variables.
I am currently on the chapter in an Arduino cookbook about mathematical functions, so it gave various examples of code. I am trying to get the "if...else" statement to round to the nearest integer in the serial monitor. I may need to add a "Serial.available" and "Serial.read" in order for it to work.