How to get the exact output "math error"? - c

Actually i am trying to get exact output "math error"when i run the program i can't exactly finf what i am actually looking for.
#include <stdio.h>
#include<math.h>
int
main ()
{
int a,b,c,d,m,n;
float x1,x2;
printf("enter value of integer :");
scanf("%d %d %d %d %d %d",&a,&b,&c,&d,&m,&n);
x1=(m*d-b*n)/(a*d-c-d);
x2=(n*a-m*c)/(a*d-c*d);
if(a*d-c*d==0)
{
printf("Math error");
}
else
{
printf("value of x1=%f\n",x1);
printf("value of x2=%f\n",x2);
}
return 0;
}

It looks like you're checking whether a*d-c*d==0 after you've used it as the denominator in the expressions to calculate x1 and x2. If that division causes a runtime divide-by-zero error the program might be crashing with other error output before it ever gets to your check.
To avoid that, you can put your if block above the lines where x1 and x2 are calculated. You should also end the program in the event of the error since further computation is invalid in that case. Of course, you need to keep the code in the else block below the lines that compute x1 and x2; you can just get rid of the else since at this point you know for sure the computation is valid.
Note: choosing d and c = 0 guarantees that your denominators will be zero (the denominators are actually different, I assume this is a typo, but c=0 and d=0 makes them both zero anyway).

You are doing integer division (n*a-m*c)/(a*d-c*d) before the check a*d-c*d==0, so you cannot avoid division by zero to get "Math error" printed.
Also what is in the printf is "Math error" with large M, not expected "math error" with small m.
Try this:
#include <stdio.h>
#include<math.h>
int
main ()
{
int a,b,c,d,m,n;
float x1,x2;
printf("enter value of integer :");
if(scanf("%d %d %d %d %d %d",&a,&b,&c,&d,&m,&n)!=6)
{
printf("input error");
}
else
if(a*d-c*d==0)
{
printf("math error");
}
else
{
x1=(m*d-b*n)/(float)(a*d-c*d);
x2=(n*a-m*c)/(float)(a*d-c*d);
printf("value of x1=%f\n",x1);
printf("value of x2=%f\n",x2);
}
return 0;
}
What I fixed:
Added checking if the input is successful.
Moved the divisions after the check a*d-c*d==0.
Fixed the message "math error".
Changed a*d-c-d to a*d-c*d because I think it is what you want.
Added casting to float to avoid truncations which you may not like.

Related

Program to Armstrong Number of 'n' digits is giving wrong output for only 153

My program to check Armstrong Number of 'n' digits is giving a wrong output, only when the input is 153.
Here is my code.
#include<stdio.h>
#include<math.h>
int main()
{
int p, k, n, t, sum, n1, m;
printf("Enter the number: ");
scanf("%d", &n);
n1=n;
for(p=0, k=1; n/k>=1; ++p, k*=10);
printf("\nThe number of digits: %d", p);
for(sum=0; n>0; n/=10)
{
t= n%10;
printf("\n\nThe base and power: %d and %d", t, p);
m=pow(t, p);
printf("\nThe calculated no is: %d", m);
sum+=pow(t, p);
printf("\nThe sum is: %d", sum);
}
printf("\n\t The original number is : %d", n1);
printf("\n\t The calculated number is: %d", sum);
if(n1==sum)
printf("\n\t%d is an armstrong number\n", n1);
else
printf("\n\t%d is not an armstrong number\n", n1);
return 0;
}
The program is getting 152 when it does the math and is therefore giving a wrong output. I have printed every step to find the exact point of error.
I have used power function instead of for loops
I cannot use t* t*t as this program is for Armstrong numbers of "n" digits, and not only 3
I am compiling the program using Code Blocks 16.01
The problem is, it is calculating the cube of 5 as 124.
Interestingly I am getting the correct answer(125) when I use the power function to calculate the cube of 5 in a separate, simple program.
I also checked the code given here -->https://www.programiz.com/c-programming/examples/check-armstrong-number which is also giving the wrong output. The answers to the somewhat similar questions that I found on this website didn't solve the problem.
Well, I'm not able to reproduce the said problem. I do get the correct result for input 153, i.e. that it is an Armstrong number.
It could be some floating point rounding error due to use of pow (though I would find that strange in this specific case).
For a task like this one, you should not use floating point. Use the largest integer type available. Not only do you avoid nasty rounding errors but you also increases the range of input values that your program can handle.
So, I like to address this part:
I cannot use t* t*t as this program is for Armstrong numbers of "n" digits, and not only 3
You can easily write a function that calculates t^n using integer math. Here is an example:
#include<inttypes.h>
uint64_t intpow(uint64_t t, uint64_t p)
{
uint64_t result = 1;
while(p>0)
{
result = result * t;
--p;
}
return result;
}
Notice: In its current form the function lacks overflow detection as I wanted to keep the function simple.
There are Two ways to solve.
1) Use round() function which will give the nearest integer (because there is some error in floating point calculation in codeblocks).
2) Declare your sum variable as float or double because then it will convert into perfect floating point precision.

Why does my C program keep giving me 1 as the error?

I ran it, and everything seems to be fine--except that it keeps giving me a margin of error of 1. Why is it doing this?
The program is supposed to prompt the user to input an estimation for the cube root of 3, and it uses Newton's method of approximation to show how many attempts it took to get to the approximation. After 500 attempts or a margin of error less than 0.000001, it's supposed to exit the loop. Why, though, doesn't the margin of error change?
Here's my code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
float a, i, e; //declare float variables
printf("Consider the function f(x) = x^3 - 3 = 0.\n");
printf("Simplifying, we get x^3 = 3.\n");
printf("Simplifying it further, we get x = 3^(1/3).\n");
printf("Enter your estimate of the root: ");
scanf("%f", &a); //prompt user to guestimate
printf("So you're saying that x = %f.\n", a);
i=0; //initiate attempt counter
e=abs((a-pow(3, (1/3)))/pow(3, (1/3))); //margin of error formula
while (e>=0.000001 && i<=500) //initiate while loop with above expressions
{
if (a!=pow(3, (1/3)))
{
printf("Attempt %f: ", i);
a = a - (pow(a, 3) - 3)/(3*pow(a, 2));
printf("%f, ", a);
printf("%f margin of error\n", e);
i=i+1;
}
else
break;
}
}
abs() deals with ints and will return an int, you need fabsf().
In the same way, pow() is for doubles, you should use powf().
Another mistake is writing 1/3 and expecting 0.333... as a result. 1 and 3 are int literals, so the operation performed is integer division. You need to use float literals, such as 1.0f/3.0f.
That's it for type compatibility. I can see another error however : you expect e to somehow remember its formula and reapply it automagically. That's not how imperative languages work : when you write e = something, "something" is calculated and stored in eĀ once and for all. You're doing it correctly for a, now just bring e=abs(...); inside the while loop to update it each time.

Small error getting to me sqrt function

I am writing this program to find the square root of a number. While defining the function mysqrt(). I am using the Newton-Raphson method. in the if() I use fabs(blah data blah) < 0.001 for relative error EX. if error is less than .1% the answer is correct. When I compile the code below
I get error line 27: called object '5.0e-1' is not a function.
I am absolutely lost as to what it is referring to. Please help Thank you.
I know there is a sqrt() function but this is for an extra credit assignment I have the majority of it written but cannot correct this error.
#include <stdio.h>
#include <math.h>
double mysqrt(double a);
int main()
{
double a, result;
printf("Enter a number to find the square root of: ");
scanf("%d", &a);
result = mysqrt(a);
printf("The square root of %d is %d \n", a, result);
}
double mysqrt(double num)
{
double x, new_x;
if((fabs(((x+1) - x)/(x+1)))<0.001)
{
for(x=2; x != num;)
{
new_x=(x+1);
new_x=(0.5(x+(num/x)));
x=new_x;
}
}
else
{
return new_x;
}
}
You forgot multiplication sign here:
new_x=(0.5(x+(num/x)));
This is a quite common error and when you see "... is not a function.", it means somewhere you have ...() which is most often a forgotten multiplication.
Also your program hard to read because of lots of parentheses, why not to write:
new_x = 0.5 * (x + num/x);
In addition, this:
(fabs(((x+1) - x)/(x+1))) < 0.001
is equivalent to:
fabs(1/(x+1)) < 0.001
Do your simplifications on paper, it will make your program more readable and errors easier to spot.

Determining if a float has a fractional part?

Here is the problem: The game Totals can be played by any number of people. It starts with a total of 100 and each player in turn makes an integer displacement between -20 and 20 to that total. The winner is the player whose adjustment makes the total equal to 5. Using only the three variables given:
total
adjustment
counter
Here is what I have so far:
#include <stdio.h>
int main (void)
{
int counter=0;
float adj;
int ttl=100;
printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");
while (ttl!=5)
{
printf("YOUR ADJUSTMENT?");
scanf("%f",&adj);
counter++;
if (adj<=20 && adj>=-20)
{
ttl=ttl+adj;
printf("The total is %d\n",ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
printf("The game is won in %d steps!",counter);
}
What I need:
When a decimal number is entered it goes to the else. How do I determine if a float has a fractional part.
You can cast the float to an int and then compare it to your original variable. If they are the same there was no fractional part.
By using this method, there is no need for a temporary variable or a function call.
float adj;
....
if (adj == (int)adj)
printf ("no fractional!\n");
else
printf ("fractional!\n");
Explanation
Since an int cannot handle fractions the value of your float will be truncated into an int (as an example (float)14.3 will be truncated into (int)14).
When comparing 14 to 14.3 it's obvious that they are not the same value, and therefore "fractional!" will be printed.
#include <stdio.h>
#include <math.h>
int main ()
{
float param, fractpart, intpart;
param = 3.14159265;
fractpart = modff (param , &intpart);
return 0;
}
http://www.cplusplus.com/reference/clibrary/cmath/modf/
modff finds the fractional part, so I guess testing whether it's equal to 0 or null will answer your question.
if you want to know whether a real number x has no fractional part, try x==floor(x).
I am only learning C so tell me if I am wrong, please.
But if instead of using
scanf("%f",&adj);
if you use:
scanf("%d%d", &adj, &IsUndef);
Therefore if the user typed anything other than a whole integer &IsUndef would not equal NULL and must have a fractional part sending the user to else.
maybe.
Using scanf() is problematic. If the user typed -5 +10 -15 -15 on the first line of input, then hit return, you'd process the 4 numbers in turn with scanf(). This is likely not what you wanted. Also, of course, if the user types +3 or more, then the first conversion stops once the space is read, and all subsequent conversions fail on the o or or, and the code goes into a loop. You must check the return value from scanf() to know whether it was able to convert anything.
The read-ahead problems are sufficiently severe that I'd go for the quasi-standard alternative of using fgets() to read a line of data, and then using sscanf() (that extra s is all important) to parse a number.
To determine whether a floating point number has a fractional part as well as an integer part, you could use the modf() or modff() function - the latter since your adj is a float:
#include <math.h>
double modf(double x, double *iptr);
float modff(float value, float *iptr);
The return value is the signed fractional part of x; the value in iptr is the integer part. Note that modff() may not be available in compilers (runtime libraries) that do not support C99. In that case, you may have to use double and modf(). However, it is probably as simple to restrict the user to entering integers with %d format and an integer type for adj; that's what I'd have done from the start.
Another point of detail: do you really want to count invalid numbers in the total number of attempts?
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter=0;
int ttl=100;
printf("You all know the rules now lets begin!!!\n"
"\n\nWe start with 100. What is\n");
while (ttl != 5)
{
char buffer[4096];
float a_int;
float adj;
printf("YOUR ADJUSTMENT?");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
break;
if (sscanf("%f", &adj) != 1)
break;
if (adj<=20 && adj>=-20 && modff(adj, &a_int) == 0.0)
{
counter++; // Not counting invalid numbers
ttl += adj;
printf("The total is %d\n", ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
if (ttl == 5)
printf("The game is won in %d steps!\n", counter);
else
printf("No-one wins; the total is not 5\n");
return(0);
}
Clearly, I'm studiously ignoring the possibility that someone might type in more than 4095 characters before typing return.

simplify complex roots

i have made a program to compute roots of quauation but it does not simplify the roots.can anyone help me to simplify them
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int a,b,c;
float d,d2;
printf(" Enter a,b and c:");
scanf("%d %d %d",&a,&b,&c);
d=b*b-4*a*c;
if(d<0)
{
printf("(%d+i%d)/%d\n",-b,sqrt(-d),2*a) ;
printf("(%d-i%d)/%d\n",-b,sqrt(-d),2*a);
}
else
{
printf("(%d+%d)/%d\n",-b,sqrt(d),2*a);
printf("(%d-%d)/%d\n",-b,sqrt(d),2*a);
}
getch();
}
You can't compute the square root of a negative number. d is negative and you're trying to find its square root. The whole point of complex solutions and the imaginary unit i is to write -1 as i^2, and then when d < 0 you have:
sqrt(d) = sqrt(i^2 * (-d)) = i*sqrt(-d)
So change to this:
if(d<0)
{
printf("(%d+i%lf)/%d",-b,sqrt(-d),2*a);
printf("(%d-i%lf)/%d",-b,sqrt(-d),2*a);
}
I don't know why you had parantheses around your printf arguments, I removed those.
The second %d should also be changed to %lf since sqrt returns a double.
If you want to compute square roots tof negative numbers, find a C99 compiler (basically, anything besides MSVC will do), include <complex.h> header, use complex data type and csqrt function.
http://en.wikipedia.org/wiki/Complex.h

Resources