Mathematical task with point numbers - c

I just started to study about C Programing.
I want to write a program to solve this mathematical task (1/2*r2*3.14)
This is the code that I wrote:
#include <stdio.h>
#include <conio.h>
main()
{
int r=5;
float sum;
sum = 1/2*r^2*3.14;
printf("%f", sum);
getch();
}
but there is an error and I don`t know what the mistake is.
First I thought that there is something wrong about the number 3.14, but when I changed it to 3 the program ran but the answer was 6.0000 but it should be 37.5

In C there is no operator for power calculation. ^ is used as XOR operator. You need to use library function pow for power calculations.
sum = 1.0 / 2 * pow(r,2) * 3.14;
Note that I changed 1/2 to 1.0/2 because 1/2 will always give 0 and the result you will get is 0.

^ is bitwise XOR operator. You have to use pow() for your purpose
sum = 1.0/2.0*pow(r,2)*3.14;
Your code will give you 6.000. Because ^ is using as xor operator
1/2*r^2*3 = (0)d ^ (6)d = (000)b ^ (110)b = (110)b = (6)d
But, 3.14 instead of 3 will give you error
1/2*r^2*3.14
Because, Xor operator don't take double as operand

The ^ operator is not for power raising you can write it explicitly
#include <stdio.h>
#include <conio.h>
main()
{
int r=5;
float sum;
/* 1/2 * r^2 * pi <- this is the expression */
sum = 1.57 * r * r;
printf("%f", sum);
getch();
}
the expression has no meaning in the program except for someone reading it, so you can add a comment and write the values directly.
And in case you are going to raise to a higher power just use the pow() function.
Also, if you skip the .0 the compiler assumes the values as integers, and 1/2 is 0.5 truncated it yeilds 0, 1./2 would also work, but not 1/2.

Related

Why is pow() function in C giving wrong answer when it is odd exponential of 10 in a loop? [duplicate]

This question already has answers here:
Why pow(10,5) = 9,999 in C++
(8 answers)
Closed 2 years ago.
#include <stdio.h>
#include <math.h>
int main()
{
int loop, place_value=0, c = 5;
for(loop = 0; loop < c; loop++)
{
place_value = 0;
place_value = pow(10, loop);
printf("%d \n", place_value);
}
return 0;
}
This code gives
10
99
1000
9999
Why is 99 and 9999 there in 3rd and 5th line instead of 100 and 10000 respectively?
When asking for power normally, it gives right answer.
#include <stdio.h>
#include <math.h>
int main()
{
printf ("%d", (int) pow (10,3 ));
return 0;
}
1000
pow is a difficult routine to implement, and not all implementations give good results. Roughly speaking, the core algorithm for pow(x, y) computes a logarithm from (a part of) x, multiplies it by y, and computes an exponential function on the product. Doing this in floating-point introduces rounding errors that are hard to control.
The result is that the computed result for pow(10, 4) may be something near 10,000 but slightly less or greater. If it is less, than converting it to an integer yields 9999.
When you use arguments hard-coded in source code, the compiler may compute the answer during compilation, possibly using a different algorithm. For example, when y is three, it may simply multiply the first argument by itself, as in x*x*x, rather than using the logarithm-exponent algorithm.
As for why the low result happens with the odd numbers you have tested, consider what happens when we multiply 5.45454545 by various powers of 10 and round to an integer. 5.45454545 rounds down to 5. 54.5454545 rounds up to 55. 545.454545 rounds down to 545. The rounding up or down is a consequence of what fraction happens to land beyond the decimal point. For your cases with pow(10, loop), the bits of the logarithm of 10 may just happen to give this pattern with the few odd numbers you tried.
pow(x, y) function translate more or less to exp(log(x) * y), which will give a result that is not quite the same as x ^ y.
In order to solve this issue you can round this:
round(pow(x, y))
The rule of thumb: never use floating point functions (especially such a complicated ones like pow or log) with integer numbers.
Simply implement integer pow
unsigned intpow(unsigned x)
{
unsigned result = 1;
while(x --) result *= 10;
return result;
}
it will be much faster or even (the fastest one)
int intpow1(unsigned x)
{
const static unsigned vals[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, /* ... */};
#if defined(CHECK_OVERFLOW)
if(x >= sizeof(vals)/ sizeof(vals[0])) return -1;
#endif
return vals[x];
}

Program always outputs 0 value

#include <stdio.h>
void volume()
{
float pi=3.14,r,v;
printf("\nEnter the radius: ");
scanf("%f",&r);
v=(1/3)*pi*r*r*r;
printf("%f",v);
}
int main()
{
volume();
}
This is C program to find volume using functions.
Compiler shows no error or warnings but the output is always zero.
you have zero here due to 1/3 is integer division = 0
replace v=(1/3)*pi*r*r*r; with v=(1.f/3.f)*pi*r*r*r;
That's because anything multiplied by 0 is 0, and 1/3 is 0.
1/3 is 0 because both 1 and 3 are literals of type int, and dividing two integers results in an integer again.
Fix: 1.0/3.0 because 1.0 and 3.0 are floating point literals, so you get floating-point division.
It's due to the fact that 1 / 3 is done as integer division because both operands are type int(a). So the final result is zero.
You can get the intended effect simply by ensuring one of the operands is non-integer, such as with:
v = (1.0f / 3) * pi * r * r * r;
That will work, because it results in a float (inside the parentheses) of 0.333.... However, there's absolutely no real reason why you need to parrot the equation shown in text books, you can achieve the same result with the simpler:
v = pi * r * r * r / 3;
Because all those variable are floating point, the result of the final something / 3 is also done as floating point.
And, just some quick advice, you may want to consider using double types rather than float. The float type generally uses less space but, unless you have large arrays of them, it's not usually a problem. The double type gives a much greater range and precision.
In addition, 3.14 is not really that precise a value for pi. Most implementations will define an M_PI constant in math.h for you to use but it's not mandated by the standard. So, you can use something like this to get a more accurate value:
#include <stdio.h>
#include <math.h>
// Define if implementation doesn't provide.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static void GetRadiusAndPrintVolume(void) {
printf("\nEnter the radius: ");
double radius;
scanf("%lf", &radius);
double volume = M_PI * radius * radius * radius / 3;
printf("Volume for radius %f is %f\n", radius, volume);
}
int main() {
GetRadiusAndPrintVolume();
}
And, finally, you may want to check that equation of yours. Though you don't say explicitly, it very much looks like it's supposed to be the volume of a sphere.
If that is the case, the formula should be 4/3 π r3 rather than 1/3. Hence the statement would be:
double volume = M_PI * radius * radius * radius * 4 / 3;
(a) If you're interested, this is all covered by the "Usual arithmetic conversions" section of the C standard (section 6.3.1.8 in C11):
Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result.
It then goes on to list what happens for specific cases, which is generally that the "lesser" (in terms of its range and/or precision) operand is upgraded to the same type as the "greater" operand. That's the basic idea though, if you want the full picture, you should refer to the previously mentioned section.
In your specific case, since both operands of 1 / 3 are of type int, the calculation and the result is done as an int, meaning it truncates the fractional part (giving zero).
Because 1/3 is not 0.3333 in C, it is 0.
Solution:
#include <stdio.h>
void volume()
{
float pi=3.14,r,v;
printf("\nEnter the radius: ");
scanf("%f",&r);
v=(((float)1)/3)*pi*r*r*r;
printf("%f",v);
}
int main()
{
volume();
}

geometric series in c, wrong solution

I'm getting a wrong solution for this series: (-1/4)^(n+1)*(z-1)^n
For |z-1|<4 should the series tend to converge to -1/3+z
For z=0.5 should be the solution -2/7, but if i try to plot with c, the result is 0...
Here is my code:
#include <stdio.h>
#include <math.h>
int main(){
double sum=0;
int n;
for(n=0;n<=100000;n++){
sum+=pow((-1/4),(n+1)) * pow((0.5-1),n);
}
printf("sum= %f\n",sum);
}
Problem right here:
sum+=pow((-1/4),(n+1)) * pow((0.5-1),n);
-1 is an integer literal, and so is 4; hence, (-1/4) is -0, and not -0.25 (which was probably what you wanted to use). Use floating point literals like -1.0 if you want them in C!
-1/4 will result to 0 as its an integer division, use floats instead:
(float)-1/4
1/4 refers to the euclidian division hence 0 obtained.
Use sum+=pow((-1.0/4.0),(n+1)) * pow((0.5-1),n); and you get the good results sum= -0.285714

Exponent not working properly in C

When i run the following code
/*Program to find the greatest common divisor of two nonnegative integer
values*/
#include <stdio.h>
int main(void){
printf(" n | n^2\n");
printf("-----------------\n");
for(int n = 1; n<11; n++){
int nSquared = n^2;
printf("%i %i\n",n,nSquared);
}
}
The table that gets returned to the terminal displays as follows
n | n^2
-----------------
1 3
2 0
3 1
4 6
5 7
6 4
7 5
8 10
9 11
10 8
why does the "n^2" side generate the wrong numbers? And is there a way to write superscripts and subscripts in C, so I do not have to display "n^2" and can display that side of the column as "n²" instead?
Use pow function from math.h.
^ is the bitwise exclusive OR operator and has to nothing to do with a power function.
The ^ is the XOR operation. You'd either want to use the math.h function "pow", or write your own.
^ is the bitwise xor operator. You should use the pow function declared in the math.h header.
#include <stdio.h>
#include <math.h>
int main(void) {
printf(" n | n^2\n");
printf("-----------------\n");
for(int n = 1; n < 11; n++){
int nSquared = pow(n, 2); // calculate n raised to 2
printf("%i %i\n", n, nSquared);
}
return 0;
}
Include the math library by the flag -lm for gcc compilation.
As others have pointed out, the problem is that ^ is the bitwise xor operator. C has no exponentiation operator.
You're being advised to use the pow() function to compute the square of an int value.
That's likely to work (if you're careful), but it's not the best approach. The pow function takes two double arguments and returns a double result. (There are powf and powl functions that operator on float and long double, respectively.) That means that pow has to be able to handle arbitrary floating-point exponents; for example, pow(2.0, 1.0/3.0) will give you an approximation of the cube root of two.
Like many floating-point operations, pow is subject to the possibility of rounding errors. It's possible that pow(3.0, 2.0) will yield a result that's just slightly less than 9.0; converting that to int will give you 8 rather than 9. And even if you manage to avoid that problem, converting from integer to floating-point, performing an expensive operation, and then converting back to integer is massive overkill. (The implementation might optimize calls to pow with integer exponents, but I wouldn't count on that.)
It's been said (with slight exaggeration) that premature optimization is the root of all evil, and the time spent doing the extra computations is not likely to be noticeable. But in this case there's a way to do what you want that's both simpler and more efficient. Rather than
int nSquared = n^2;
which is incorrect, or
int nSquared = pow(n, 2);
which is inefficient and possibly unreliable, just write:
int nSquared = n * n;

Solving n! with C (equation error somewhere)

In my quest to learn C I've come across a task which is causing me a few problems. I need to make an equation for the approximate value of the formulae n!, which can be described as:
n! = n^n*e^(-n)*sqrt(2(2*n+1/3)*PI), however I simply cannot get my values to corrospond with the actual value. 5! = 120ish
I can get a value of some 148ish
Can't figure out where my code is wrong:
#include <stdio.h>
#include <math.h>
#define PI 3.14156
#define E_CONST 2.7828
int main ()
{
double num;
double calc, first, second, third, fourth;
printf("Give an int: ");
scanf("%lf", &num);
first = pow(num , num);
second = pow(E_CONST, -num);
third = (2 * num + 1/3);
fourth = sqrt(2*third*PI);
//calc = first * second * fourth;
calc = pow(num, num) * pow(E_CONST, -num) * sqrt(2*(2*num+(1/3))*PI);
printf("Input: %f", num);
printf("1: %.2f\n2: %.10f\n3: %.8f\n4: %.2f\n", first, second, third, fourth);
printf("\nInt was: %.2f\n\nApproximate number: %.5f", num, calc);
return 0;
}
Feel like i have tried everything. The code is a bit messy, but it's because I've scrambled so much with it now.
3.14156 is a bad value for PI: it's better to use 3.1416, or 3.14159, or 4 * atan(1), or, for POSIX implementations, M_PI.
2.7828 is a very bad value for e: it's better to use 2.7183, or exp(1), or, for POSIX implementations, M_E.
1/3 is integer division, the result is 0: it's better to use 1.0/3.
Also your approximation is incorrect. The correct approximation is
n^n * e^(-n) * sqrt((2*n+1/3)*PI)
It seems you fell into the integer division trap with 1/3, which has the value 0. You need to write this with floating point constants as 1.0 / 3.0.
You probably need to type 1.0/3.0 to get one third.

Resources