Edit script for user input rather than internal input - c

I have a simple script and it works fine. My question is, how can I get my results to display in a reduced simplified fraction? Also, at this point I am defining the values myself, is there a way to have the script ask the user to input the numerator and denominator for the different fractions used?
The posted script worked wonders for me in regards towards asking and performing the operations, so I am very thankful for that. It did not reduce the fractions, am I still missing something?
#include<stdio.h>
#include<math.h>
#include<string.h>
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
int input(char* prompt) {
int res;
printf("%s: ", prompt);
scanf("%d", &res);
return res;
}
main()
{
int add,sub,mul,dd;
int add1,sub1,mul1,dd1;
int a,b,c,d;
int fac = gcd(add, add1);
a=input("Please enter the numerator for your first equation:");
b=input("Please enter the denominator for your first equation:");
c=input("Please enter the numerator for your second equation:");
d=input("Please enter the denominator for your second equation:");
add=(a*d+b*c);
add1=(b*d);
add /=fac;
add1/=fac;
printf("\The sum of your fractions is: %d/%d",add,add1);
sub=(a*d-b*c);
sub1=(b*d);
printf("\nThe difference of your fractions is: %d/%d",sub,sub1);
mul=(a*c);
mul1=(b*d);
printf("\nThe product of your fractions is: %d/%d",mul,mul1);
dd=(a*d);
dd1=(b*c);
printf("\nThe quotient of your fractions is: %d/%d",dd,dd1);
}

for each possible factor from 2 to min (numerator, denominator)
while this factor evenly divides both numerator and denominator
numerator /= factor;
denominator /= factor;
This will do it. Actually, you could go up to min (sqrt (numerator), sqrt (denominator)), and that would work too.
Since you need it several times, best put it into a function and call it on each of your results.

Look up the Euclidean algorithm. This is faster to compute the gcd of two numbers than trying out all possible prime factors.
int gcd(int a, int b) {
return (0==b) ? a : gcd(b, a % b);
}
or
int gcd(int a, int b) {
while(0!=b) { int r = a % b; a=b; b=r; }
return a;
}
Then apply, for instance for the sum, as
fac = gcd(add, add1);
add /=fac;
add1/=fac;
to get the reduced numbers.
To your other question, use the atoi function to transform argument string into numbers or use the scanf function to prompt for input. Be aware that no input verification is done by the C functions.
#include ...
int gcd(int a, int b) { ... }
int input(char* prompt) {
int res;
printf("%s: ", prompt);
scanf("%d", &res);
return res;
}
int main() {
...
int a,b,c,d;
a = input("Number for a");
b = input("Number for b");
...

Related

Calculate sin(x) and cos(x) using Taylor Series in C [duplicate]

I have been struggling with this code and just do not seem to grasp what I am doing wrong.
The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!
Here is my code thus far:
#include <stdio.h>
#include <math.h>
float factorial(int n){
if (n==0)
return 1;
else
return 2*n*factorial(n-1);
}
int main (){
float i, n;
float sum=0;
printf("Enter desired interger: ");
scanf("%f", &n);
for (i=0; i<=1; i++)
sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));
printf("The value is %f\n", sum);
return 0;
}
I still working on it, any info or help will be much appreciated!
edit:
Just fixed it guys, this is new format I had to use for my professor:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf(" x mycos(x) cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}
Thank you all for your explanations, they helped out Immensely!
One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.
For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).
another thing I see, is that your denominator is the n! rather than (2 * n)!
For efficiency, I might also implement the factorial routine as follows:
unsigned int factorial(int n){
unsigned int product = 1;
for(int I = 1; I <= n; I++) product *= I;
return product;
}
The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.
float factorial(int n){
float product = 1;
for(int I = 1; I <= n; I++) product *= (float)I;
return product;
}
I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.
Considering computation expense, you need to stop calculating the series at a point. The more you go, the more precise the result will be, but the more your program spends time. How about this simple program:
#include <stdio.h>
#include <math.h>
#define ITERATIONS 10 //control how far you go
float factorial(int n){
if (n==0)
return 1;
else
return n*factorial(n-1);
}
int main (){
float n;
float sum=0;
printf("Enter desired float: ");
scanf("%f", &n);
int c, i;
for (i=0; i<=ITERATIONS; i++) {
c = (i%2)==0? 1 : -1;
sum = sum + (c*pow(n,2*i+1))/(factorial(2*i+1));
}
printf("The value is %f\n", sum);
return 0;
}
1.) You are only multiplying even no.s in factorial function return 2*n*factorial(n-1); will give only even no.s. Instead you can replace n with 2n here- sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(2n)); This will give the correct (2n!).
2.) Check for the no, of iterations for (i=0; i<=1; i++) this will only run your loop twice. Try more no. of iterations for more accurate anwer.
Why are you calculating power etc for each item in the series? Also need to keep numbers in a suitable range for the data types
i.e. for cos
bool neg_sign = false;
float total = 1.0f;
float current = 1.0f;
for (int i = 0; i < length_of_series; ++i) {
neg_sign = !neg_sign;
current = current * (x / ((2 * i) + 1)) * (x / (( 2 * i) + 2));
total += neg_sign ? -current : current;
}
EDIT
Please see http://codepad.org/swDIh8P5
#include<stdio.h>
# define PRECISION 10 /*the number of terms to be processed*/
main()
{
float x,term=1,s=1.0;
int i,a=2;
scanf("%f",&x);
x=x*x;
for(i=1;i<PRECISION;i++)
{
term=-term*x/(a*(a-1));
s+=term;
a+=2;
}
printf("result=%f",s);
}
Your factorial() function actually calculates 2n.n!, which probably isn't what you had in mind. To calculate (2n)!, you need to remove the 2* from the function body and invoke factorial(2*n).

C Power function negative exponent without pow()

I'm trying to make a little power calculator for learning purposes in C without using pow,
but it always returns 0.00 when exponent is negative, please help.
full code:
#include<stdio.h>
//* power caculator function
int power(x,y)
{
float p=1.00;
int i;
if (y<0){
y=-1*y;
x=1/x;
}
for (i=1;i<=y;i++)
{
p=p*x;
}
return p;
}
//* main gets input, calls power caculator and prints result'
int main()
{
int b;
int e;
float p;
printf("enter base");
scanf("%d",&b);
printf("enter exponent");
scanf("%d",&e);
p=power(b,e);
printf("%d to the power of %d is %.2f",b,e,p);
return 0;
}
//* I am NOOB
You are using integers to hold decimal values, in this case with x and with the return type of the power function.
try:
float power(x,y)
{
float p=1.00;
float xx = (float)x;
int i;
if (y<0){
y=-1*y;
xx=1/xx;
}
for (i=1;i<=y;i++)
{
p=p*xx;
}
return p;
}
define data types of x and y explicitly and then adjust the return data type.

-1.#IND00 output for certain input values

I'm trying to write a code that will take x as input and give cos(x) as output, using maclaurin's series.I'm using a while loop until the difference of two consecutive results is less then 0.001. I'm using double type to accomodate larger values.
the code works when x is in range [-2,2], but if x is greater or less than this range the ouput is -1.#IND00. Why is it happening? is the output value out of range ? how can i fix this ??
my code is :
#include <stdio.h>
double abs(double a);
double power(double p, int q);
int fact(int a);
int main()
{
int i=1,j=2*i;
double x,s=1.0,p,l=0.001;
printf("Enter x: ");
scanf("%lf", &x);
p = s+ power(-1,i) * power(x,j) / fact(j);
while (abs(p-s)>l){
i++; j=2*i;
s=p;
p = s+ power(-1,i) * power(x,j) / fact(j);
}
printf("cos(%f) = %f", x,p);
return 0;
}
double abs(double a)
{
if (a>=0) return a;
else return (-a);
}
double power(double p, int q)
{
int i;
double a=1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
int fact(int a)
{
int i,p=1;
if (a==0 || a==1) return 1;
else
while (a!=1){
p=p*a;
a--;
}
return p;
}
update your scanf function to
scanf("%lf", &x);
Also you need to check pow and fact, these functions could overflow. Especially, fact which only use int.
As a larger |x| is use, more terms are needed and fact() overflows and strange results follow. Use double.
// int fact(int a)
double myfact(double p, int q) {
int i;
double a = 1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
Eventually with values somewhere larger |x| > 30, other limitations kick in using this method. The limitation is due to precision and not range. For large values a significantly different algorithm should be used.
Potential conflict between int abs(int j) in <stdlib.h>. The prototyped may be found via stdio.h and conflicts with OP double abs(double a). In any case, abs() is a standard library function and OP should avoid that function name. Also recommend renaming power().
// double abs(double a)
double myabs(double a)

rip off a number out of a fraction

I am working on a project and I have an idea on how to start. Basically this is how the program runs:
$ ./rulerbuddy 2.25
2.25 is exactly 2 1/4
So, I kind of have the idea that I need first to rip off the whole number which in this case is '2' then start manipulating the fraction to get the result. My question is how can I rip off that whole number from the decimal fraction? Any ideas, steps, guide is appreciated. Thank you.
Take out the whole number and consider only the decimal part (do a sscanf(input, "%d.%d", &intPart, &fracPart) to take them apart).
Count the digits after the decimal point; your starting fraction is digits/10^number of digits, i.e. in your case 25/100;
Now you can simplify it finding the greatest common divisor (e.g. with Euclid algorithm) and dividing both terms by it.
Quick example of how this can be implemented:
#include <stdio.h>
#include <math.h>
struct Fraction
{
int n;
unsigned int d;
};
int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a-b*(a/b));
}
void simplify(struct Fraction * f)
{
int divisor=gcd(f->n, f->d);
f->n/=divisor;
f->d/=divisor;
}
int main(int argc, char * argv[])
{
int intPart;
unsigned int fracPart;
struct Fraction f;
if(argc<2)
{
puts("Not enough arguments.");
return 1;
}
if(sscanf(argv[1], "%d.%u", &intPart, &fracPart)!=2)
{
puts("Invalid input.");
return 2;
}
f.n=fracPart;
f.d=fracPart!=0?(int)pow(10., floor(log10(fracPart)+1)):1;
simplify(&f);
printf("%s is exactly: %d %d/%u\n", argv[1], intPart, f.n, f.d);
return 0;
}
if(num < 0)
num = num * (-1);
then
Just type cast the number explicitly to `int`
Use the standard library function floor
#include <math.h>
int WholeNumber(double number)
{
return (int)floor(number);
}
int main(void)
{
int N;
N = WholeNumber(2.25);
printf("The Whole part is %d\n", N); // this will print 2
}
Try a regex
http://rubular.com/r/KkE34B4ODQ
I've set that up to work for your example, you may need to alter it based on what your program provides for whole numbers (ie.e 2 0/1) or whatever.
The first group is the whole
second is numerator
third is denominator

largest number without conditional operator

can any one please elaborate how to find largest of four numbers without using conditional operator.for 3 numbers i have done but for four numbers how to write different comparisons.
There is a standard way to compute min or max in 2's complement arithmetics without using conditionals:
int max(int a, int b){
unsigned diff = b - a; // negative if a > b
int sign = -(diff >> (sizeof(int) * CHAR_BIT - 1)); // -1 if a > b, 0 otherwise
return (a & sign) | (b & ~sign);
}
it can be easily scaled.
void main()
{
int a, b;
printf("Enter a and b:");
scanf("%d %d", &a, &b);
printf("Maximum number is %d", max(a, b));
getch();
}
int max(int a, int b)
{
int c, temp;
c = a - b;
temp = c + abs(c);
// To check if the difference is negative or not
if(temp) //As suggested by R..
return b;
else
return a;
}
This code is for compare two numbers. Make this comparison for all numbers.
you can find max of two number a,b by using following trick:
(abs(a+b)+abs(a-b))/2
Extend the trick for as many numbers you want.

Resources