Input a value for a scanf(), but nothing happens - c

I'm writing some code as part of a few assignment exercises to learn C programming from absolute basics, and I've run into a problem, which is probably quite simple to solve, but I'm completely stuck! I'm writing a program to implement a basic Newton's method for differentiation. Whenever I input an initial value to the scanf(), the program simply stops, doesn't return anything, terminate or freeze. Any help would be great.
Here is my code to start with:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//function to be used f(x) = cos(x)-x^3
//f'(x) = -sin(x)-3x^2
int main()
{
double x, xold;
printf("Enter an initial value between 0 and 1\n");
scanf("%lf",&xold);
double eps = 1e-12;
x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2)))));
while (fabs(x-xold)>eps)
{
x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
}
printf("The answer is %.12lf",x);
return 0;
};

In your while loop:
x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
the value of the = right operand is always the same, how could you exit the loop once you enter it?

Actually the thing is you are not updating your xold variable. Try the below modified code for your problem, see if I have done correctly:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double x, xold;
printf("Enter an initial value between 0 and 1\n");
scanf("%lf",&x);
double eps = 1e-12;
x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2)))));
while (fabs(x - xold)>eps)
{
xold = x;
x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2))));
}
printf("The answer is %.12lf\n",x);
return 0;
}

Related

How do i tell if an output an integer or not in C

i Have this homework about a superhero triangle, from what i got if the Area an integer data, then it's a superhero triangle, if it's not then it's not a superhero triangle.
The problem is, how do i determine if the output an integer or not
Thank you
Note : English is not my main language, sorry for the lack of vocabulary to describe it
Well I believe your calculation is all with doubles, because you are not sure of the result maybe an int maybe double. but you just need to know if it's really a double or an int, in your case 2.0 is an int of course, so I made this simple example for you
#include <iostream>
int isFloat(double n) {
return n - int(n) > 0;
}
int main(void) {
double x = 2.1;
if(isFloat(x)) {
std::cout << "it's a float";
}else {
std::cout << "it's an int";
}
return 0;
}
output
it's a float
Assuming you are just trying to check if a number is an integer (not necessarily the type but just that it has no decimal values... ex: 5.00 is an integer)
You could use the math.h standard library like this:
#include <stdio.h>
#include <math.h>
int main()
{
double output_value = 1.27;
if(fmod(output_value, 1.00) != 0)
//This is not an integer
else
//This is an integer
}
Clearly, if a number is not evenly divisible by 1, it is not an integer.
This seems like the simplest solution to me.

Approximating the value of pi in C using Viete's Formula

My assignment this week in my CS class is create a program to approximate for pi using Viète's Formula. I've been trying to start for the past hour or so, but I'm honestly not even sure how to begin. All the work I have gotten done doesn't work.
I'm assuming my professor wants us to use the "while" loop, as we've been using it a lot in class lately. We've also been using "if" statements a lot, although I'm not sure if we need to use those here.
Can anyone help me find a starting off point or explain how I could go about doing this?
//here is some of the work i have attempted that doesn't work because i don't know what to do
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double n,pi,f,i;
printf("enter the number of iterations to approximate for pi\n");
scanf("%lf\n", &n);
pi = 2 / f;
i = 1;
f = sqrt(2);
while (i<=n)
{
}
To start with the code you posted:
1) You don't want i and n to be of type double Change them to int
2) You should always check the value returned by scanf Like: if (scanf(%d) != 1) {// add error handling here ...}
3) pi = 2 / f; is undefined behavior as f is uninitialized
Then your assignment:
I'll not give you a complete solution but instead give you a hint so you can continue your work.
The formula needed can be found here: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence
Your first task is to calculate a[n] given that
a[1] = sqrt(2)
a[n] = sqrt(2 + a[n-1])
You can do that using a while-loop (though I would prefer a for-loop). It could be like:
#include <stdio.h>
#include <math.h>
int main()
{
int n, i;
n = 5;
i = 1;
double an = sqrt(2);
while(i <= n)
{
printf("a%d = %.10f\n", i, an);
an = sqrt(2 + an);
++i;
}
return 0;
}
This gives you:
a1 = 1.4142135624
a2 = 1.9615705608
a3 = 1.9975909124
a4 = 1.9998494037
a5 = 1.9999905876
So now that you know how to calculate a1, a2, a3, ... you just need to put it together using:
(image from: https://en.wikipedia.org/wiki/Viète%27s_formula#Interpretation_and_convergence)
and find pi.

Why it asks the same but in the code theres only 1 printf()?

Im sorry but im just learning c, probably its easy to fix but i dont know how
In the code i just have 1 printf but in the terminal shows the same question 2 times. But finally the result is correct.
#include <stdio.h>
#include <math.h>
double lfDemanaTaxa(){
double i;
double d;
printf("Quant es la taxa interes nominal?\n");
scanf("%lf",&i);
d = i/100;
return d;
}
double lfDemanaMensualitat(){
double n;
scanf("%lf",&n);
return n;
}
int main(){
double a,b,c,TAE;
a = (1+lfDemanaTaxa()/lfDemanaMensualitat());
b = pow(a,lfDemanaMensualitat());
c = b -1;
TAE = c * 100;
printf("El TAE total es %.2lf%% \n", TAE);
return 0;
}
You call the lfDemanaMensualitat() function twice, and it does one call to printf(), so of course you're going to have two print-outs.
If you wanted to only call it once and store the value, you can something like this:
const double t = lfDemanaMensualitat();
const double a = (1 + lfDemanaTaxa()) / t;
const double b = pow(a, t);
And then compute c and TAE like you already do. This just saves the result of lfDemanaMensualitat() in a temporary variable called t.
By the way you should know that scanf() can fail, if the user enters things that don't match the specified conversion. You must check the return value to make sure it succeeded before relying on the input.

Equation having sqrt ,abs and the derivative on c

First, i would like to tell you that english isnt my nature language so maybe a word or meaning i am not express it right.The problem now is i recently did one exercise and the question was to use the Newton-Raphson method for sqrt.Anyway, i think this(sqrt) i have done it i am not sure about it.I couldnt do the derivative.Also,i think i have some mistakes on my code if you could fix it i would be greatful.The equation is
x=sqrt(num)=>x*x=num=>f(x,num)=x*x-num=0
#include<stdio.h>
#include<stdlib.h>
#include <math.h> /* i use it for pow */
#definde f(x) ((x*x-num)/2x) /* this is the equation */
main(){
double num=8; /* i put what ever i want so i put 8 */
double result;
double oldx=2; /* i put what ever i want so i chose to put 2 */
double x;
x=num/2;
result=sqrt(x);
printf("num= %d x= %16.lf\n",num,result);
while(abs(x-oldx)>pow(10,-15)){ /* |x-oldx|> pow(10,-15).I am not sure about abs here */
x=oldx; /* i give to x the price of oldx */
printf("x=%lf",x); /* its double so i use lf */
x=(pow(x,2)-num)/2*x; /* #definde f(x) ((x*x-num)/2x) this is it but i wrote it in that way.Maybe i dont know it could be false */
printf("x=%lf",x);
}
printf("x= %lf result= % 16.lf ");
system("pause");
}
There are numerous mistakes in your code:
abs should be fabs.
The while loop keeps setting x=oldx for each iteration and oldx never changes, so the loop never makes any progress. It should really set oldx=x.
/2*x does not divide by 2*x as you require, because * and / have the same operator precedence. You need to replace it with /(2*x) or /2/x.
At each step, you are calculating xₙ₊₁ = f(xₙ) / fʹ(xₙ), but the correct formula is xₙ₊₁ = xₙ − f(xₙ) / fʹ(xₙ).
In addition, there is no need to use the pow function to calculate 10⁻¹⁵ or x² when a literal constant or a simple multiplication will do.
Here is a complete solution:
#include <stdio.h>
#include <math.h>
int main(void) {
double num = 8; /* i put what ever i want so i put 8 */
double result;
double x;
double oldx;
double residual;
unsigned int iterations=0;
result = sqrt(num);
x = num / 2; /* initial guess */
printf("sqrt(%g)=%.16g\n", num, result);
do {
printf("x%u=%.16g\n", iterations, x);
iterations++;
oldx = x;
x = x - ((x * x - num) / (2 * x));
residual = x - oldx;
} while (fabs(residual) > 1e-15);
printf("x%u=%.16g residual=%.16g\n", iterations, x, residual);
return 0;
}

Surface area of a hexagon

I am currently attempting to learn C, and have made this program to calculate the area of a regular hexagon:
#include <stdio.h>
#include <math.h>
void main(){
int a;
float ans;
scanf("%d", &a); // get length of side
ans = ((pow(a, (1/3)))/2)*(a*a);
printf("%f", ans);
}
However, it outputs seemingly random numbers.
Firstly your code doesn't compile (Missing semicolon) and also you should use int main() instead of void main().
Secondly your formula also wrong, the area of a regular hexagon of side length a is calculated as ((3√3)/2)*a².
Thirdly Expression like 1/3 always yield zero as both are integer, to get expected behavior make one of them float/double. like 1.0/3 or (float)1/3 etc.
#include <stdio.h>
#include <math.h>
int main()
{
int a;
float ans;
scanf("%d", &a); // get length of side
ans = (3*sqrt(3)/2.0)*a*a;
printf("%f", ans);
}

Resources