I am trying to convert decimal number to binary number using recursion.
But I am getting wrong output...I tried to debug the program and got stuck with "pow()".
I inserted many printf statements to see the status of the variables...
Here is my program...
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
int n,k;
int z;
long b,j;
long binary(int,int);
printf("Enter a Number : ");
scanf("%d",&n);
printf("Binary Equivalent is : ");
k=log2(n);
b=binary(n,k);
z=pow(10,k);
printf("\n\nb=%d ,z=%d",b,z);
}
long binary(int n,int c)
{
int a,np;
static long b=0;
if(n<=1){
b=(n%2)*(int)pow(10,c)+b;
printf("\n nmod2=%d\nb=%ld\nc=%d\nn=%d ",(n%2),b,c,n);
return b;
}
else{
a=n%2;
np=pow(10,c);
b=a*np+b;
printf("\n a=%d,np=%d \n nmod2=%d \n b=%ld \n c=%d \n n=%d ",a,np,(n%2),b,c,n);
binary(n/2,--c);
}
}
Output is:
Enter a Number : 5
Binary Equivalent is :
a=1,np=99
nmod2=1
b=99
c=2
n=5
a=0,np=10
nmod2=0
b=99
c=1
n=2
nmod2=1
b=100
c=0
n=1
b=100 ,z=100
why the "pow(10,c)" in binary() when c=2 equals 99 why not 100 as in main()?
The problem is here:
(int)pow(10,c)
The result is around 100, but rounding it down with (int) can get you either 99 or 100 depending on the roundoff error of pow.
This is a handy function lround in math.h that should help you. It rounds a number towards the closest integer, rounding 0.5 towards zero.
Alternatively, you could define:
int my_round(double f) {
return (int)(f+0.5);
}
Adding 0.5 and rounding down looks like rounding to the closest integer.
The pow() function is a floating-point function, which tends to screw up such stuff. You shouldn't use it for integers without proper rounding to compensate.
Multiple problems.
As others have point out that the result of pow(10,c) is the problem. A good pow() would return exactly 100.0 for pow(10,2). It is reasonable to expect that behavior from pow(), but a cautious programmer would do as others suggest and round-to-nearest a floating point number to an int.
Round to nearest is best handle with a library function. Should one want to roll your own:
int IRound(double f) { return (f > 0.0) ? (int)(f + 0.5) : (int)(f - 0.5); }
long binary(int n,int c) does not return a value when n > 1. Suspect return binary(n/2,--c) is wanted.
The static long b=0; is a bad way to deal with recursion. long binary(int n,int c) would nominally correctly run only once. A second call, b would not necessarily start at 0.
Given pow() is flaky, log2() may need special care too.
Related
I know this problem has been on the internet for a while but i cant seem to find how to stop my program from rounding the 3rd decimal.
the answer output is 4524.370 and should be 4524.369
also, i know my equations are stupid and could be simplified but im lazy
//Tanner Oelke CSE155E
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void){
double v, t; //base variables
double sq1, sq2; //calculation variable for square root
printf("Please enter the given air temperature in Fahrenheit:");
scanf("%lf", &t);
//unessecary equations but it works
sq1=(57*t+297);
sq2=(sq1/247);
v=1086*sqrt(sq2);
printf("%.3lf\n", v);
return 0;
}
With an input of "70.0" the result is 4524.369754... which displays as "4524.370" - What OP gets.
With an input of "69.999975" the result is 4524.369002... which displays as "4524.369" - what OP wants.
If OP expects "70.0" to result in "4524.369", then some minor adjustment to the formula is needed. The precision of double is at least 10 significant digits and often is 15+. Even doing this in float then f(70.0)--> 4524.370.
Else OP has the wrong expectation.
Response to OP's comment:
"to shorten the decimal place to 3 spots without rounding". Hmmm seems strange to want this:
// properly rounded result
printf("%.3lf\n", v);
// shorten to 3 places without rounding
double v3 = floor(v*1000.0)/1000.0;
printf("%.3lf\n", v3);
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.
I made a program to find if a number belongs to fibonacci series or not and if it does whats its position.Whenever i type a number the if Condition goes wrong.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int i,x=1,y=1,z,num;
clrscr();
printf("Enter a number to find in fibonacci series:");
scanf("%d",&num);
/*to find if the number is a part of fibonacci series or not*/
if((isdigit(sqrt(5*num*num+4)))||(isdigit(sqrt(5*num*num-4)))) //<-- this if!
{//belongs to fibo!
for(i=1; ;i++)
{
if(x==num)
break;
z=x+y;
x=y;
y=z;
}
printf("%d is the %d term of fibonacci series.",num,i);
}
else
printf("Dear user,The entered number is not a part of the fibonacci series.");
getch();
}
You're misunderstanding the isDigit function.
isDigit takes an ASCII character code and returns true if it represents a decimal digit.
You want to check whether the double returned by sqrt is an integer.
There's an obvious error in your use of isdigit(). That function (usually macro) is used to tell if a character is one of the characters 0..9 - certainly your code is dealing with numbers consistently and there's no need for character checking.
You'll want to take a closer look at what you're trying to accomplish. You're welcome to ask us which C functions might be suitable.
EDIT:
Ah, you want to know if that funky expression is an integer value. Alas, there's no built-in function for that. I haven't tested this, but I'd write
double a = (funky expr);
if (a == rint(a)) ...
... where rint() is a function that returns the double that's the nearest integer value to the given argument.
Why are you using isdigit? The result of sqrt is a double - you need to check that value directly.
You want to check if 5 * num * num + 4 or 5 * num * num - 4 is a perfect square. A function that will do this is:
int is_perfect_sq(double d)
{
double sqroot = rint(sqrt(d));
return (sqroot * sqroot) == d;
}
Note - this is a good disproof of the notion that you should never compare floating point numbers for equality. In this case, it is fine, since a "perfect square" must be an integer.
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
I have written the following sample code to find the harmonic value of N. (1+1/2+1/3+...1/N). Read the comments in the code written in BOLD and help me to find why is this happening.
#include <stdio.h>
float harmonic(float n, float har) {
if(n==0) {
return 0;
}
if(n==1) {
printf("%f\n", har+1.0f);***/* This prints value 1.5000*/***
return har+1.0f;
}else{
harmonic(n-1, (har+(1/n)));
}
}
int main()
{
printf("%f\n", harmonic(2, 0.0f)); **/* But this prints value nan(Not a Number)*/**
return 0;
}
Thanks,
Naga
I think you want to do:
return harmonic(n-1, (har+(1/n)));
My first thought was that you should almost never compare floats with simple equality so "if(n==0)" should be "if(n<=EPSILON)" and "if(n==1)" should be "if(n<= 1.0f + EPSILON)" where EPSILON is a small positive fraction, maybe 1.0e-5. Depends on how much precision you can depend on.
But then I realized that n should be an int. Cast it to a float before the division. As the comparisons with "n" stand you risk infinite recursion.
Consider using a double instead of a float.
Matthew Flaschen's answer gets to real reason you get the NaN message. The original code doesn't return anything from the "else" so the caller is probably reading garbage from the stack. Hence, the NaN.