I'm relatively new to C and I am trying to get a program to run. It's a program that lists all primes from 1 - 1000. The way I compile it is by typing gcc Primes.c into the command line and running it in NppExec.
Code:
#include <stdio.h>
#include <math.h>
int x;
int bool = 1;
int y;
main() {
for (x = 2; x <= 100; x++) {
bool = 1;
for (y = 0; y <= floor(x/2); y++) {
if (x % y == 0) {
bool = 0;
}
}
if (bool == 1) {
printf("%d\n", x);
}
}
}
I type:
NPP_SAVE
CD $(CURRENT_DIRECTORY)
C:\MinGW32\bin\gcc.exe -g "$(FILE_NAME)"
a
into the box and then execute. A window will pop up and say a.exe has stopped working. Any idea's on how to fix this?
There is a bug and many smaller issues in your code:
You should not define x, bool and y as global variables, define these variables inside the body of the main function.
The prototype for main is int main(void) or int main(int argc, char *argv[]). main() is an obsolete form that is no longer supported by the C standard. gcc will accept it but clang will not by default. You should also add return 0; at the end of main: although it was made implicit in C99, it is better style and more portable to older compilers.
You should not use bool as a variable name, bool is usually used as a type name, name your flag prime.
You should loop until 1000 as instructed.
y <= floor(x / 2) does not work as expected: x / 2 is an integer expression, it already has the value you expect, passing it to floor will convert it as a double and return the same value, y will be automatically converted to double for the comparison. All this is unnecessary, y <= x / 2 suffices. floor is the only function used from <math.h>, you can remove this include file too.
Note that your condition will let the program perform way too many iterations, you should instead use y * y <= x.
Initializing y to 0 will cause a division by zero when you compute x % y, invoking undefined behavior, the crash you observe. You must initialize y to 2 because all numbers are divisible by 1.
You should exit the loop when you detect that x is composite, avoiding unnecessary iterations.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int x, y, prime;
for (x = 2; x <= 1000; x++) {
prime = 1;
for (y = 2; y * y <= x; y++) {
if (x % y == 0) {
prime = 0;
break;
}
}
if (prime == 1) {
printf("%d\n", x);
}
}
return 0;
}
You have
for (y = 0; y <= floor(x/2); y++) {
if (x % y == 0) {
You initialize y to zero, then you directly divide by y (i.e. zero). Division by zero doesn't work, it will crash your program.
The problem are these 2 lines:
for (y = 0; y <= floor(x/2); y++) {
if (x % y == 0) {
What do you expect to get with 2 % 0?
As per the standard:
C99 6.5.5p5 - The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
The crash is because of the Modulo operator when y is 0.
how to check if there is a division by zero in c
Related
#include <stdio.h>
int main()
{
int x = 2, y = 0;
int m = (y |= 10);
int z = y && m;
printf("%d\n", z);
return 0;
}
Above program gives me output as 1. Below code is giving me output 0 but what is the reason for different outputs here?
#include <stdio.h>
int main()
{
int x = 2, y = 0;
int z = y && (y |= 10);
printf("%d\n", z);
return 0;
}
In
int z = (y |= 10);
y is masked with 10 so set to 10, so y && m is a boolean worth 1 because both y and m are non-zero, assigned to z
Now, in
int z = y && (y |= 10);
y == 0 so && short-circuits, not evaluating the right hand part and not changing the value of y. Therefore, z is set to 0.
Had you used:
int z = y & (y |= 10);
this would have depended on how/in which order the compiler evaluates the operands (implementation defined behaviour to get 0 or 10)
note that && short-circuiting doesn't evaluate the second parameter if the first is zero for a very good reason:
if ((pointer != NULL) && pointer->value == 12) { do_something(); }
this condition checks if the value is 12 but only if the pointer is non-NULL. If the second expression was evaluated first, this could crash.
This program works in handling positive integers, but not on negative integers. How can I fix this one? Thanks!
By the way, is my code good or not? Is there a better way on getting the quotient and remainder without using the '/', '%', and '*' operators?
#include <stdio.h>
int divide(int x, int y, int quotient);
int getRem(int x, int y, int quotient, int product, int count,
int remainder);
int main()
{
int dividend, divisor, quotient = 0, product = 0;
int remainder, count = 0;
scanf("%d %d", ÷nd, &divisor);
printf("\nQuotient: %d", divide(dividend, divisor, quotient));
quotient = divide(dividend, divisor, quotient);
printf("\nRemainder: %d", getRem(dividend, divisor, quotient, product, count, remainder));
}
int divide(int x, int y, int quotient)
{
while (x > 0)
{
x -= y;
quotient++;
}
if (x != 0)
return quotient - 1;
else
return quotient;
}
int getRem(int x, int y, int quotient, int product, int count, int remainder)
{
while (count != y)
{
product += quotient;
count++;
remainder = x - product;
}
return remainder;
}
By the way, is my code good or not?
Well, there's room for improvements...
First of all - don't pass unnecessary variables to your function!
A function that shall divide x by y shall only take x and y as arguments. Whatever variables you need inside the function shall be defined inside the function.
So the first step is to change your divide function to be:
int divide(int x, int y)
{
int quotient = 0; // use a local variable
while (x > 0)
{
x -= y;
quotient++;
}
if (x != 0)
return quotient - 1;
else
return quotient;
}
Another (minor) issue is the two return statements. With a simple change of the while statement that can be avoided.
int divide(int x, int y)
{
int quotient = 0; // use a local variable
while (x >= y) // notice this change
{
x -= y;
quotient++;
}
return quotient;
}
Also notice that a call like divide(42, 0); will cause an infinite loop. So perhaps you should check for y being zero.
The algorithm can be improved - especially for large numbers - but I guess you want a simple approach so I stick to your basic algorithm.
... but not on negative integers. How can I fix this one?
A simple approach is to convert any negative input before entering the loop and maintain a counter to remember the number of negative numbers. Something like:
int divide(int x, int y)
{
int quotient = 0;
int negative = 0;
if (x < 0)
{
x = -x; // Make x positive
++negative;
}
if (y < 0)
{
y = -y; // Make y positive
++negative;
}
while (x >= y) // Both x and y are positive here
{
x -= y;
quotient++;
}
return (negative == 1) ? -quotient : quotient;
}
int main(void)
{
printf("%d\n", divide( 5, 2));
printf("%d\n", divide( 5,-2));
printf("%d\n", divide(-5, 2));
printf("%d\n", divide(-5,-2));
printf("%d\n", divide( 6, 2));
printf("%d\n", divide( 6,-2));
printf("%d\n", divide(-6, 2));
printf("%d\n", divide(-6,-2));
return 0;
}
Output:
2
-2
-2
2
3
-3
-3
3
You can apply the same kind of changes to the function getRem and I'll leave that part for you as an exercise...
However, notice that your current function uses quotient without any benefit. The function (only handling positive numbers) could simply be:
int getRem(int x, int y) // requires x >= 0 and y > 0
{
while (x >= y)
{
x -= y;
}
return x;
}
Is there a better way of getting the quotient and remainder without using the '/', '%', and '*' operators?
The majority of the time, I think, by far the best way of computing quotient and remainder is with the / and % operators. (It's their job, after all!)
If you need both quotient and remainder at the same time, there's also the div function, which does exactly that. (Its return value is a struct containing quot and rem members.) It's a bit cumbersome to use, but it might be more efficient if it means executing a single divide instruction (which tends to give you both quotient and remainder at the machine level anyway) instead of two. (Or, these days, with a modern optimizing compiler, I suspect it wouldn't make any difference anyway.)
But no matter how you do it, there's always a question when it comes to negative numbers. If the dividend or the divisor is negative, what sign(s) should the quotient and remainder be? There are basically two answers. (Actually, there are more than two, but these are the two I think about.)
In Euclidean division, the remainder is always positive, and is therefore always in the range [0,divisor) (that is, between 0 and divisor-1).
In many programming languages (including C), the remainder always has the sign of the dividend.
See the Wikipedia article on modulo operation for much, much more information on these and other alternatives.
If your programming language gives you the second definition (as C does), but you want a remainder that's never negative, one way to fix it is just to do a regular division, test whether the remainder is negative, and if it is, increment the remainder by the divisor and decrement the quotient by 1:
quotient = x / y;
remainder = x % y;
if(remainder < 0) {
reminder += y;
quotient--;
}
This works because of the formal definition of integer division with remainder:
div(x, y) → q, r such that y × q + r = x
If you subtract 1 from q and add y to r, you get the same result, and it's still x.
Here's a sample program demonstrating three different alternatives. I've encapsulated the little "adjust quotient for nonnegative remainder" algorithm as the function euclid(), which returns the same div_t type as div() does:
#include <stdio.h>
#include <stdlib.h>
div_t euclid(int, int);
int main()
{
int x = -7, y = 3;
printf("operators: q = %d, r = %d\n", x/y, x%y);
div_t qr = div(x, y);
printf("div: q = %d, r = %d\n", qr.quot, qr.rem);
qr = euclid(x, y);
printf("euclid: q = %d, r = %d\n", qr.quot, qr.rem);
}
div_t euclid(int x, int y)
{
div_t qr = div(x, y);
if(qr.rem < 0) {
qr.quot--;
qr.rem += y;
}
return qr;
}
To really explore this, you'll want to try things out for all four cases:
positive dividend, positive divisor (the normal case, no ambiguity)
negative dividend, positive divisor (the case I showed)
positive dividend, negative divisor
negative dividend, negative divisor
This program works in handling positive integers, but not on negative integers. How can I fix this one?
When you call :
divide(-10, 3) or divide(-10, -3) the while loop condition while(x > 0) will be false
divide(10, -3) the while loop will be infinite loop because of the statement x -= y. (x) will be increase by the value of (y)
is my code good or not?
Your code is need to be organized:
in the main function you need to pass only the necessary parameters. in the divide function why you pass the quotient. the quotient will be calculated inside the function. so that you should edit the prototype to int divide(int x, int y);.
the same thing with getRem function you should edit the prototype to int getRem(int x, int y);.
in the main function you are calling the divide function twice to print the quotient and to save the quotient in the variable quotient. instead you should call the function only one time and reuse the returned value.
After the previous points your main and functions prototypes should be as follow:
#include <stdio.h>
int divide(int x, int y);
int getRem(int x, int y);
int main()
{
int dividend, divisor, quotient = 0;
scanf("%d %d", ÷nd, &divisor);
quotient = divide(dividend, divisor);
printf("\nQuotient: %d", quotient);
printf("\nRemainder: %d", getRem(dividend, divisor));
}
Now lets analyze the function divide. The first point, In math when multiplying or dividing, you actually do the operation on the sign as doing on the number. the following is the math rules for multiply or divide the sign.
negative * positive -> negative
positive * negative -> negative
negative * negative -> positive
negative / positive -> negative
positive / negative -> negative
negative / negative -> positive
The second point is the while loop. You should divide until (x) is less than (y).
As an example: suppose x = 7, y = 3 :
after first loop x -> 4 and y -> 3
after second loop x -> 1 and y -> 3 so that the condition should be while(x >= y)
so now you should first manipulate the sign division after that the numbers division. as follows.
int divide(int x, int y)
{
int quotient = 0;
//save the resulting sign in the sign variable
int sign = 1;
int temp = 0;
/* sign division */
// negative / positive -> negative
if((x < 0) && (y >= 0)){
sign = -1;
temp = x;
x -= temp;
x -= temp;
}// positive / negative -> negative
else if((x >= 0) && (y < 0)){
sign = -1;
temp = y;
y -= temp;
y -= temp;
}// negative / negative -> positive
else if((x < 0) && (y < 0)){
temp = x;
x -= temp;
x -= temp;
temp = y;
y -= temp;
y -= temp;
}
while (x >= y)
{
x -= y;
quotient++;
}
if(sign < 0){
temp = quotient;
quotient -= temp;
quotient -= temp;
}
return quotient;
}
Lets go into the getRem function. The remainder(%) operation rules is as follows:
negative % (negative or positive) -> negative
positive % (negative or positive) -> positive
note: the result follows the sign of the first operand
As an Example:
suppose x = -10 and y = 3, x / y = -3, to retrieve (x) multiply y and -3, so x = y * -3 = -9 the remainder is equal to -1
suppose x = 10 and y = -3, x / y = -3',x = y * -3 = 9` the remainder is equal to 1
now apply the previous points on the getRem function to get the following result:
int getRem(int x, int y)
{
int temp, remSign = 1;
if(x < 0){
remSign = -1;
temp = x;
x -= temp;
x -= temp;
}
if(y < 0){
temp = y;
y -= temp;
y -= temp;
}
while (x >= y)
{
x -= y;
}
if(remSign < 0){
x = -x;
}
return x;
}
You can to combine the two operation in one function using pointers for remainder as follows:
#include <stdio.h>
int divide(int x, int y,int * rem);
int getRem(int x, int y);
int main()
{
int dividend, divisor, quotient = 0;
int rem;
scanf("%d %d", ÷nd, &divisor);
quotient = divide(dividend, divisor, &rem);
printf("\nQuotient: %d", quotient);
printf("\nRemainder: %d", rem);
}
int divide(int x, int y, int * rem)
{
int quotient = 0;
int sign = 1;
int remSign = 1;
int temp = 0;
if((x < 0) && (y >= 0)){
sign = -1;
remSign = -1;
temp = x;
x -= temp;
x -= temp;
}
else if((x >= 0) && (y < 0)){
sign = -1;
temp = y;
y -= temp;
y -= temp;
}
else if((x < 0) && (y < 0)){
temp = x;
x -= temp;
x -= temp;
temp = y;
y -= temp;
y -= temp;
}
while (x >= y)
{
x -= y;
quotient++;
}
if(remSign < 0){
*rem = -x;
}else{
*rem = x;
}
if(sign < 0){
temp = quotient;
quotient -= temp;
quotient -= temp;
}
return quotient;
}
One of my C assignments was it to write an approximation of arctan(x) in the language C. The equation which I should base it on is
arctan(x)=\sum {k=0}^{\infty }(-1)^{k} \tfrac{x^{2k+1}}{2k+1}
In addition x is only defined as -1<=x<=1.
Here is my code.
#include <stdio.h>
#include <math.h>
double main(void) {
double x=1;
double k;
double sum;
double sum_old;
int count;
double pw(double y, double n) {
double i;
double number = 1;
for (i = 0; i < n; i++) {
number *= y;
}
return(number);
}
double fc (double y) {
double i;
double number = 1;
for (i = 1; i <= y; i++){
number *= i;
}
return(number);
}
if(x >= (-1) && x <= 1) {
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
printf("My result is: %.17lf\n",sum);
printf("atan(%f) is: %.17f\n", x, atan(x));
printf("My result minus atan(x) = %.17lf\n", sum - atan(x));
} else {
printf("x is not defined. Please choose an x in the intervall [-1, 1]\n");
}
return 0;
}
It seemingly works fine with every value, except value 1 and -1. If x=1, then the output ends with:
...
7207 || 0.78543285189457468
7208 || 0.78536
Whereas the output should look more like this. In this case x=0.5.
25 || 0.46364760900080587
26 || 0.46364760900080587
My result is: 0.46364760900080587
atan(0.500000) is: 0.46364760900080609
My result minus atan(x) atan(x) = -0.00000000000000022
How can I improve my code so that it can run with x=1 and x=-1.
Thanks in advance.
PS: I use my own created pw() function instead of pow(), because I wanted to bybass the restriction of not using pow() as we didn't had that in our lectures yet.
PPS: I'd appreciate any advice as to how to improve my code.
In each iteration, you add (-1)k • x2k+1 / (2k+1), and you stop when there is no change to the sum.
If this were calculated with ideal arithmetic (exact, infinitely precise arithmetic), it would never stop for non-zero x, since you are always changing the sum. When calculating with fixed-precision arithmetic, it stops when the term is so small it does not change the sum because of the limited precision.
When |x| is less than one by any significant amount, this comes quickly because x2k+1 gets smaller. When |x| is one, the term becomes just 1 / (2k+1), which gets smaller very slowly. Not until k is around 253 would the sum stop changing.
You might consider changing your stopping condition to be when sum has not changed from sum_old very much rather than when it has not changed at all.
if(x >= (-1) && x <= 1) {
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
Comparing doubles can be tricky. The conventional way to compare doubles is to test within epsilon. There should be an epsilon value defined somewhere, but for your purposes how many digits are enough to approximate? If you only need like 3 or 4 digits you can instead have
#define EPSILON 0.0001 //make this however precise you need to approximate.
if(x >= (-1) && x <= 1) {
for(k=0; fabs(sum - sum_old) > EPSILON; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
If the issue is that -1,1 iterate too many times either reduce the precision or increase the step per iteration. I am not sure that is what you're asking though, please clarify.
I think the cause of this is for a mathematical reason rather than a programming one.
Away from the little mistakes and adjustments that you should do to your code, putting x = 1 in the infinite series of arctan, is a boundary condition:
In this series, we add a negative value to a positive value then a negative value. This means the sum will be increasing, decreasing, increasing, ... and this will make some difference each iteration. This difference will be smaller until the preciseness of double won't catch it, so the program will stop and give us the value.
But in the sum equation. When we set z = 1 and n goes from 0 to ∞, this will make this term (-1^n) equal to 1 in one time and -1 in the next iteration. Also,
the value of the z-term will be one and the denominator value when n approaches infinity will = ∞ .
So the sum several iterations will be like +1/∞ -1/∞ +1/∞ -1/∞ ... (where ∞ here represents a big number). That way the series will not reach a specific number. This is because z = 1 is a boundary in this equation. And that is causing infinite iterations in your solution without reaching a number.
If you need to calculate arctan(1) I think you should use this formula:
All formulas are from this Wikipedia article.
Here is some modifications that make your code more compact and has less errors:
#include <stdio.h>
#include <math.h>
#define x 0.5 //here x is much easier to change
double pw(double, double); //declaration of the function should be done
int main() { //the default return type of main is int.
double k;
double sum = 0 ; //you should initiate your variables.
double sum_old = 1 ; //=1 only to pass the for condition first time.
//you don't need to define counter here
if(x < -1 || x > 1){
printf("x is not defined. Please choose an x in the interval [-1, 1]\n");
return 0;
}
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
printf("%.0f || %.17lf\n", k, sum);
}
printf("My result is: %.17lf\n",sum);
printf("atan(%f) is: %.17f\n", x, atan(x));
printf("My result minus atan(x) = %.17lf\n", sum - atan(x));
return 0;
}
double pw(double y, double n) { //functions should be declared out of the main function
double i;
double number = 1;
for (i = 0; i < n; i++) {
number *= y;
}
return(number);
}
double fc (double y) {
double i;
double number = 1;
for (i = 1; i <= y; i++){
number *= i;
}
return(number);
}
I'm trying to find numbers that satisfy the clause (x - y * √ 2016) / (y + √ 2016) = 2016.
Number x and y can be rational numbers.
That's what I already tried:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int x, y;
for(x = 1; x < 10000; x++) {
for(y = 1; y < 10000; y++) {
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016) {
printf("Numbers are: %d and %d.", x, y);
}
}
}
return 0;
}
Using floating point math and brute force search to "solve" this problem is conceptionally a bad idea. This is because with FP math round-off error propagates in a non-intuitive way, and hence many equations that are solvable in a mathematical sense have no (exact) solution with FP numbers. So using FP math to approximate solutions of mathematical equations is inherently difficult.
I suggest a simplification of the problem before programming.
If one does this and only searches for integer solutions one would find that the only solutions are
x = -2016^2 = -4064256
y = -2016
Why: Just rearrange a bit and obtain
x = 2016*y + (2016 + y)*sqrt(2016)
Since sqrt(2016) is not an integer the term in the clause before the sqrt must be zero. Everything else follows from that.
In case a non-integer solution is desired, the above can be used to find the x for every y. Which even enumerates all solutions.
So this shows that simplification of a mathematical problem before attempted solution in a computer is usually mandatory (especially with FP math).
EDIT: In case you look for rational numbers, the same argument can be applied as for the integer case. Since sqrt(2016) is not a rational number, y must also be -2016. So for the rational case, the only solutions are the same as for the integers, i.e,
x = -2016^2 = -4064256
y = -2016
This is just the equation for a line. Here's an exact solution:
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
For any value of y, x is given by the above. The x-intercept is:
x = 2016*sqrt(2016)
y = 0
The y-intercept is:
x = 0
y = -2016*sqrt(2016)/(sqrt(2016)+2016)
numbers that satisfy (x - y * sqrt(2016.0)) / (y + sqrt(2016.0)) = 2016
Starting with #Tom Karzes
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
Let y = -2016
x = (sqrt(2016) + 2016)*-2016 + 2016*sqrt(2016)
x = 2016*-2016 = -4064256
So x,y = -4064256, -2016 is one exact solution.
With math, this is the only one.
With sqrt(x) not being exactly √x and peculiarities of double math, there may be other solutions that pass a C code simulation.
As a C simulation like OP's, lets us "guess" the answer's x,y are both multiples of 2016 and may be negative.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double f(int x, int y) {
double z = (x - y * sqrt(2016.0)) / (y + sqrt(2016.0));
z = z - 2016;
return z * z;
}
#define M 3000
int main() {
double best_diff = DBL_MAX;
int best_x = 0;
int best_y = 0;
int x, y;
for (x = -M; x < M; x++) {
for (y = -M; y < M; y++) {
double diff = f(x * 2016, y * 2016);
if (diff < best_diff) {
best_diff = diff;
best_x = x;
best_y = y;
}
if (diff == 0) {
printf("Numbers are: %d and %d.\n", best_x*2016, best_y*2016);
}
}
}
if (best_diff != 0.0) {
printf("Numbers are: %d and %d --> %e.", best_x*2016, best_y*2016, best_diff);
}
return 0;
}
Output
Numbers are: -4064256 and -2016.
The result from operations with floats are in general not exact.
Change:
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016)
to something like
if( fabs((x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) - 2016) < 0.00000001)
where 0.00000001 is a tolerance chosen by you.
But as pointed out, you don't want to search through the domains of more variables than necessary. Solve the math first. Using Wolfram Alpha like this we get y=(x-24192*√14)/(12*(168+√14))
I was asking about round a number half up earlier today and got great help from #alk. In that post, my thinking was to round up 4.5 to 5 but round 4.4 down to 4. And the solution given by #alk was:
int round_number(float x)
{
return x + 0.5;
}
and it works very elegantly!
In this post, I would like to discuss how to implement the ceil() function in C.
Along the same line as the last solution given by #alk, I came up with the following:
int round_up(float y)
{
return y + 0.99999999;
}
This works for all situations except when the the float number y has .00000001. I am wondering if there's any better way to do the same thing as ceil() in C.
Unless you reliably know the epsilon of float (I'm not sure standard C provides that), I think you're stuck with return (y < 0 || y == (int)y) ? y : y + 1;
This fails for negative numbers.
int round_up(float y) {
return y + 0.99999999;
}
But let's use that to our advantage. float to int conversion is a truncate toward 0.0. Thus negative numbers are doing a "round up" or "ceiling" function. When we have a positive float, convert to int noting this is a "floor" function. Adjust when y is not an integer.
(Assume y within INT_MIN ... INT_MAX.)
int ceil(float y) {
if (y < 0) {
return y; // this does a ceiling function as y < 0.
}
int i = y; // this does a floor function as y >= 0.
if (i != y) i++;
return i;
}
void ceil_test(float y) {
printf("%f %d\n", y, ceil(y));
}
The first snippet works incorrectly for negative numbers. -3.5 will be come -3, not -4. To round values properly use
int round_number(float x)
{
if (x >= 0)
return x + 0.5f;
else
return x - 0.5f
}
Even that way it's still incorrect for 2 values. See Why does Math.round(0.49999999999999994) return 1?. Note that you need to use the f suffix to get the float literal, otherwise the operation will be done in double precision and then downcast back to float
For ceiling, adding 1 is enough
int ceiling(float x)
{
if (x < 0 || (int)x == x)
return x;
else
return x + 1.0f;
}
When x is an integer, e.g. x = 3.0 (or -3.0), it returns 3 (or -3). For x = 3.1 it returns 4, for x = -3.1 it returns -3