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
Related
I'm a university student and in one of my exercises to train c programming I got stuck on an error with a print function. I used CLION which was great but now moved on into VS Code, because the teacher say it´s the most used in a professional environment. What are your thoughts on it?!
main.cpp
#include <stdio.h>
#include "complex.h"
int main (){
Complex x;
inputNmbr(x);
printNmbr(x);
return 0;
}
complex.h
#include <stdio.h>
typedef struct{
float r,i;
}Complex;
Complex inputNmbr(Complex x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &x.r, &x.i);
return x;
}
void printNmbr (Complex x){
printf("Imaginary number: %.2f +/- %.2f\n", x.r, x.i);
}
Terminal
aluno#aluno-VirtualBox:~/Desktop/Programação por objetos/P1/EX2$ ./main\
Input an imaginary number (R +/- I):
1 2
Imaginary number: 0.00 +/- 0.00
So the printf function always shows 0 0 and I´m not understanding the source of this error.
P.S. After being attacked about the C/C++ tag I´m posting the exercise (the reason why I put the both tags is related to this):
Write a module in C that allows working with complex numbers.
Create the files complex.h and complex.cpp where you should implement the following functionalities:
The definition of data structure (Complex) to represent a complex number
(r, i);
A function that reads a complex number;
A function that writes a complex number in the format: #.#+/-#.#i (where +/- depends on the sign of the imaginary part);
A function for each of the following operations:
Addition: a+bi+c+di=(a+c)+(b+d)i
Subtraction: a+bi-c+di=(a-c)+(b-d)i
Multiplication: (a+bi)*(c+di)=(ac-bd)+(bc+ad)i
Division:
(a+bi) / (c+di)=((ac+bd)/(c^2+d^2))+((bc-ad)/(c^2+d^2))i
I am not going through all your execise, however, the problem of your incorrect printf is that your struct variable x is passed "by value" to the function inputNmbr. This means that when invoking it, a copy of your variable is created and put on the function stack, and even if you modify the value inside the function, the modification is not reflected in the original variable.
A solution can be to change the input parameter of inputNmbr function so to make it a pointer. For example:
void inputNmbr(Complex * x){
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &(x->r), &(x->i));
}
In this case, your main will be:
int main (){
Complex x;
inputNmbr(&x);
printNmbr(x);
return 0;
}
Another method of doing this would be having in main:
Complex x = inputNmbr();
and in your fn definition:
Complex inputNmbr(){
Complex a;
printf("Input an imaginary number (R +/- I):\n");
scanf("%f %f", &a.r, &a.i);
return a;
}
The choice of a "return" vs using pass by address to return is stylistic but may also depend on a standard depending on your professor.
I'm having a problem with getting my code to pick up the user input of the variables number and result. The correct way the code should act is: When user puts in a positive value, code should square root this value and display the new value. As of now, there are no error messages, the code runs fine, just not the way i want it to.
It does NOT pick up any value and does not square root math either, when looking at the output.
I also need to use pointers when doing this code (weird imo). Pointers are something im very new to so i expect to get quite the critique on that department.
I have tried reading several tutorials on pointers and the understanding of sqrt but it feels like key parts of those things still confuse me.
Code: (Consists of a function squareRoot that does the math and main that handles input/output)
#include <stdio.h>
#include <math.h> //needed for sqrt()
#define POSITIVE 1 //not used atm
#define NEGATIVE 0 //not used atm
float squareRoot(float number, float * result) {
return * result = sqrt(number); //calculate the square root of a number
}
int main() {
float number = 0;
float * result = malloc(sizeof(float));
printf("Enter a float value: ");
scanf("%f", &number);
squareRoot(number, result);
if (number < 0) {
printf("Square root of a negative value is not possible.");
}
if (number > 0) {
printf("Square root if %.2f is: %.2f "), number, result;
}
return 0;
}
Any help or constructive criticism is greatly appreciated!
result is a pointer, you need to dereference it.
printf("Square root if %.2f is: %.2f ", number, *result);
If you didn't get a compiler warning for the type mismatch, increase your warning level.
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.
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.
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.