Reputation: 69
I've created a program which takes an integer x input, then loops until x is met while also taking other integer inputs. I then do various calculations, and then find a square root of a certain value. When I divide by square root however I get a 0 when I know I should be getting a different value as the maths doesn't add up.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void) {
int multiply1, multiply2, add, squareRoot;
int i;
int n;
int x;
int s;
double divide, test = 0;
scanf("%d", &x);
for (s = 0; s < x; s++) {
scanf("%d %d", &i ,&n);
}
multiply1 = i * i;
multiply2 = n * n;
add = multiply1 + multiply2;
squareRoot = sqrt(add);
printf("%d", i);
test = (i / squareRoot);
printf("Multiplication = %d\n", multiply1);
printf("Multiplication = %d\n", multiply2);
printf("Added together = %d\n", add);
printf("square root = %d\n", squareRoot);
printf("First output = %.3f\n", test);
return 0;
}
Upvotes: 1
Views: 92
Reputation: 53016
There are two things you can do,
Without changing your program, simply cast the i
and squareRoot
variables to double
test = (double) i / (double) squareRoot;
Change your program and make i
and squareRoot
a double
.
I, would choose 2 because sqrt()
returns a double
and that might cause an integer overflow.
Upvotes: 1
Reputation: 137
You are dividing two integers so the actual division returns the result rounded down. You should instead cast to double and then divide.
test = ((double)i/squareRoot);
Upvotes: 2