Square root values not being retrieved - c

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.

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.

I can't get this (simple) loop to work properly

I'm in a programming class right now, and was asked to create a program that calculated the sum of a user's input for multiple numbers--then calculate the nth root of the sum. If the number they input was less than 0, the loop is supposed to discard the less than 0 number, then ask again.
Unfortunately, no matter what number I input--it displays "Value needs to be greater than zero!" I tried putting a fflush(stdin); statement in the loop, but that didn't seem to do anything.
Here is my code. I really appreciate any and all help.
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
int mTotalNums, mNth; //amount of numbers in set
float mProd = 1, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
mNth = mTotalNums; //set the value of mTotalNums equal to mNth becuase we'll lose the original value of mTotalNums after the loop
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
}
mNroot = pow(mProd, (1 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
"%lf" is the scanf format for a double, but x is declared as float.
To scan a float, you have to use the %f format.
Note also that mTotalNums is not decremented in the loop, so that it will never
terminate.
Read the documentation of scanf(3). Since x is declared as a float, use %f as the scanf format control string. Also, take into account the result of scanf (it would be 1 if successfully read one item).
You should enable all warnings and debug info in your compiler, then learn how to use the debugger (notably to run your program step by step, display local variables, etc....).
(On Linux, if compiling with gcc -Wall -g you would get a useful warning, and the gdb debugger would be helpful...)
Try these modifications to your program (added comments with changes made)
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
//amount of numbers in set
int mTotalNums, mNth;
// Change to double for added precision
double mProd = 1.0, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
// Set the value of mTotalNums equal to mNth becuase
// we'll lose the original value of mTotalNums after the loop
mNth = mTotalNums;
// Don't forget to decrement the loop counter
while (mTotalNums-- > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else {
printf("\nValue needs to be greater than zero!\n");
}
}
// Change to 1.0 to force compiler to treat as a double
mNroot = pow(mProd, (1.0 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
You mention "calculate the nth root of the sum", but your loop is clearly tallying the cumulative product. To change it to calculate the sum, try the following additions:
// Declare a sum variable
double sum = 0;
// Sum inside your while loop
sum += x;
// Calculate the nth root of the sum instead
mNroot = pow(sum, (1.0 / mNth));
Add printf commands to see what your variables contain before you check them in your logic statements.
You also need to do something to increment/decrement your variable for your while loop... currently nothing is changing mTotalNums, so it will be an infinite loop.
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
printf("x=%d", x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
mTotalNums--;
}

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.

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