error with numbers dropping decimal places in c - c

I am in a beginner c class and when I run my code it drops some decimal places. According to my handwritten equation of the same type it should equal 99.5 can someone tell me what I'm doing wrong?
#include <stdio.h>
//create the number variable
double number = 0;
//function prototypes
double get_input();
double get_next(double one, double two);
void print_result(void);
int main(){
//get all the input needed
double x_two = get_input();
double x_one = get_input();
//calculate third
double x_three = get_next(x_one,x_two);
//calculate fourth
double x_four = get_next(x_three,x_two);
//calulate fith and set to number
number = get_next(x_four,x_three);
//print the result
print_result();
}
double get_input(void){
double number = 0;
//prompt the user for the information needed
printf("Please enter a value > ");
//take the user info and pass it back
scanf("%lf",&number);
return number;
}
double get_next(double minus_one, double minus_two){
double number = (minus_two/2)+(3*minus_one);
return number;
}
void print_result(void){
printf("The result is: %lf",number);
}
The equation is given as such
Xn =
Xn−2/2 + (3 * xn-1)
the numbers I plug in for n-2 is 2 and n-3 is 3

Your get_input() needs to return a value. return number;

Related

How to extract digits after decimal point in float and store in char Array

I refered below question but I need to extract the digits after decimal and store in char *array
1.How to store float in array of float[]
2.Extract digits in float in python
Ex:
float = 1.24456
My length of char *array is 2
Expected Output:
array[0] = 2;
array[1] = 4;
array[2] = 4;
I need to implement this in C dynamically.
You can isolate the fractional part of a float by using the function modff in <math.h>, which returns the fractional part as the function's return value and the whole-number part as an argument by reference:
float f = 3.141592f;
float numpart, fracpart;
fracpart = modff(f, &numpart);
Once you're done that, you can create a string with a conventional string-building function:
char buf[100];
snprintf(buf, 100, "%f", fracpart);
Another option is converting the entire float to a string, and then using strchr(float_str, '.') to isolate the decimal part.
Slightly more mathematical approach, but arguably less flexible would be this:
#include <stdio.h>
#include <math.h>
int main()
{
float num = 1.24456;
int num_noDecimals = (int)num; //truncate decimals in original number
float num_onlyDecimals = num - (float)num_noDecimals; //obtain only the number after decimal
int x = 4; //number of digits past decimal to extract
num_onlyDecimals = num_onlyDecimals*pow(10,x); //move extracting digits left of decimal
int digits_forArray = (int)num_onlyDecimals; //truncate remaining digits right of decimal
char arr[x];
for(int i=x-1; i > -1; i--) { arr[i] = (char)(digits_forArray%10); digits_forArray = digits_forArray/10; }
for(int i=0;i<x;i++) { printf("arr[%d] = %d\n",i,arr[i]); }
}
Hopefully it's commented well enough to understand the steps being taken here.
In my code, I removed the integer part, then I reverse the float part to integer part by multiply each number of the float part by the number 10 then I classify each digit of in the array
My code :
int main()
{
float n = 1.2445601;
int m=(int)n;
float p=n-m;
int x=7,i=0,tab[x];
while(i<x)
{
p=p*10;
i++;
}
i=6;
while((int)p!=0)
{
tab[i--]=(int)p%10;
p=p/10;
}
for(int k=0;k<x;k++)
{
printf("\narray[%d] = %d ;",k,tab[k]);
}
printf("\n");
return 0;
}
If you just want the digits after the decimal point in variable, you could just have number - floor(number)
for example, if your number was 3.25, the calculation would be 3.25 - 3. This will give 0.25

C Power function negative exponent without pow()

I'm trying to make a little power calculator for learning purposes in C without using pow,
but it always returns 0.00 when exponent is negative, please help.
full code:
#include<stdio.h>
//* power caculator function
int power(x,y)
{
float p=1.00;
int i;
if (y<0){
y=-1*y;
x=1/x;
}
for (i=1;i<=y;i++)
{
p=p*x;
}
return p;
}
//* main gets input, calls power caculator and prints result'
int main()
{
int b;
int e;
float p;
printf("enter base");
scanf("%d",&b);
printf("enter exponent");
scanf("%d",&e);
p=power(b,e);
printf("%d to the power of %d is %.2f",b,e,p);
return 0;
}
//* I am NOOB
You are using integers to hold decimal values, in this case with x and with the return type of the power function.
try:
float power(x,y)
{
float p=1.00;
float xx = (float)x;
int i;
if (y<0){
y=-1*y;
xx=1/xx;
}
for (i=1;i<=y;i++)
{
p=p*xx;
}
return p;
}
define data types of x and y explicitly and then adjust the return data type.

C loop with an increment

how can I do an increment when a range is given for conversion? Following is the code:
#include <stdio.h>
int disrange(float x, float y);
int main()
{
printf("The conversion from miles to km are:");
printf("\n");
printf("Miles kilometers");
printf("\n");
// Set the range in Miles
disrange(1,5,incr); ---> extra params increment
}
int disrange(float x, float y)
{
int a;
for(a=x; a<=y; a++){
// convert each value into km
float b = a*1.61;
printf("%d %f\n",a,b);
}
}
When the increment is 2, the print out should be conversion for 1, 3, 5. Thanks!!
int disrange(float x, float y,float inc)
{
int a;
for(a=x; a<=y; a+=inc){
// convert each value into km
float b = a*1.61;
printf("%d %f\n",a,b);
}
}
If you want it in table format, try:
int disrange(float x, float y,float inc)
{
int a;
for(a=x; a<=y; a+=inc){
// convert each value into km
float b = a*1.61;
printf("%6d\t%07.5f\n",a,b);
}
}
This will make the first field a minimum of 6 characters long, with the second 7 characters long with five after the decimal place. See here for more information on printf

returning a floating point value from a function

hey i really need help with this program.. i doesnt want return a proper answer for a negative power always return 1.. can anyone help??
The program should help the user to enter a base number and power and when executed calculates the value and displays the result
float square (float a,int b);
int main(){
int power;
float base;
printf("Please input your base number :\n");
scanf("%f",&base);
printf("Please input your power :\n");
scanf("%d",&power);
float answer = square(base,power);
printf("Your Result is :\n%f\n",answer);
system("pause");
return 0;
}
float square (float a,int b){
int counter;
float total = 1;
if (b==0){
return 1;
} else if (b>0){
for(counter=0;counter<b;counter++){
total = total*a;
}
return total;
} else {
for (counter=0;counter<b;counter++){
total = total*a;
}
total = 1 / total;
return total;
}
}
Declare total as a float instead of an int.
Also, your if's should be on b instead of a.
After that, remove all those unnecessary (float) castings.
Also, your last for for should run backwards as your initial value is less than 0.
Your square function should look like this:
float square (float a,int b){
int counter;
float total = 1;
if (b==0){
return 1;
} else if (b>0){
for(counter=0;counter<b;counter++){
total = (float)total*a;
}
return total;
} else {
for (counter=0;counter< -b;counter++){
total = (float)total*a;
}
total = 1.0 / (float)total;
return total;
}
}
You need a float for total, you need to check b instead of a in your if statements, and you need to count up to -b when it's negative.
Declare total to float and initialize it as
float total = 1.0f;
Use abs function for dealing with -ve b.
else {
for (counter=0;counter < abs(b);counter++){
total = total*a;
}
total = 1 / total;
return total;
}
and include <stdlib.h>.
See the working code Here.
This part
} else {
for (counter=0;counter<b;counter++){
total = total*a;
}
total = 1 / total;
return total;
}
ignores the fact that b is < 0.
So either you should put b = -b; in, or
for (counter=0;counter>b;counter--){
total = total / a;
}
return total;
might help you.
This does the job ;)
#include <stdio.h>
#include <math.h>
int main(){
int power;
float base;
printf("Please input your base number :\n");
scanf("%f",&base);
printf("Please input your power :\n");
scanf("%d",&power);
float answer = pow(base,power);
printf("Your Result is :\n%f\n",answer);
system("pause");
return 0;
}
Here's a cool trick:
y = a^b
ln(y) = b ln(a)
y = exp(b ln(a))
so the function should look like this:
double Power(double a, double b)
{
return exp(b*log(a));
}

Getting the fractional part of a double value in integer without losing precision

i want to convert the fractional part of a double value with precision upto 4 digits into integer. but when i do it, i lose precision. Is there any way so that i can get the precise value?
#include<stdio.h>
int main()
{
double number;
double fractional_part;
int output;
number = 1.1234;
fractional_part = number-(int)number;
fractional_part = fractional_part*10000.0;
printf("%lf\n",fractional_part);
output = (int)fractional_part;
printf("%d\n",output);
return 0;
}
i am expecting output to be 1234 but it gives 1233. please suggest a way so that i can get desired output. i want the solution in C language.
Assuming you want to get back a positive fraction even for negative values, I'd go with
(int)round(fabs(value - trunc(value)) * 1e4)
which should give you the expected result 1234.
If you do not round and just truncate the value
(int)(fabs(value - trunc(value)) * 1e4)
(which is essentially the same as your original code), you'll end up with the unexpected result 1233 as 1.1234 - 1.0 = 0.12339999999999995 in double precision.
Without using round(), you'll also get the expected result if you change the order of operations to
(int)(fabs(value * 1e4 - trunc(value) * 1e4))
If the integral part of value is large enough, floating-point inaccuracies will of course kick in again.
You can also use modf() instead of trunc() as David suggests, which is probably the best approach as far as floating point accuracy goes:
double dummy;
(int)round(fabs(modf(value, &dummy)) * 1e4)
number= 1.1234, whole=1, fraction=1234
int main()
{
double number;
int whole, fraction;
number = 1.1234;
whole= (int)number;
fraction =(int)(number*10000);
fraction = fraction-(whole *10000);
printf("%d\n",fraction);
printf("%d\n",whole);
return 0;
}
A solution for any number could be:
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
float number = 123.46244;
float number_final;
float temp = number; // keep the number in a temporary variable
int temp2 = 1; // keep the length of the fractional part
while (fmod(temp, 10) !=0) // find the length of the fractional part
{
temp = temp*10;
temp2 *= 10;
}
temp /= 10; // in tins step our number is lile this xxxx0
temp2 /= 10;
number_final = fmod(temp, temp2);
cout<<number_final;
getch();
return 0;
}
Use modf and ceil
#include <stdio.h>
#include <math.h>
int main(void)
{
double param, fractpart, intpart;
int output;
param = 1.1234;
fractpart = modf(param , &intpart);
output = (int)(ceil(fractpart * 10000));
printf("%d\n", output);
return 0;
}

Resources