When I input a negative integer the output will not result to it's cube value. I'm confused what should I do? here is my code:
#include <stdio.h>
int main()
{
int n, i, cube;
printf("Enter an integer: ");
scanf("%d",&n);
while (i<=n)
{
cube = i*i*i;
i++;
}
printf("The cube of %d = %d\n ", n, cube);
return 0;
}
I would assume you'd want to compute the cube of a number by using a loop that iterates 3 times.
int n, cube, i;
printf("Enter an integer: ");
scanf("%d",&n);
cube = 1;
i = 0;
while (i < 3)
{
cube = cube * n;
i++;
}
printf("%d\n", cube);
i
is not initialized.You simply need:
long long cube(int n)
{
return n * n * n;
}
int main(void)
{
int x = -21;
while(x++ < 40)
printf("n=%d n^3 = %lld\n", x, cube(x));
}
Or if you need to use while loop:
long long cube(int n)
{
long long result = 1;
int power = 3;
while(power--) result *= n;
return result;
}
Or full of while
s and no multiplication.
long long cube(int n)
{
long long result = 0;
unsigned tempval = abs(n);
while(tempval--) result += n;
tempval = abs(n);
n = result;
while(--tempval) result += n;
return result;
}
You just want the cube of 1 number?
i = 0;
cube = 1;
while (i<3)
{
cube *= n;
i++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.