how to make negative numbers into positive - c

I am having the negative floating point number as:
a = -0.340515;
to convert this into positive number I used the abs() method as:
a = abs(a);
the result is a = 0.000000;
But I need the result as 0.340515.
Can anyone tell me how to do this.

abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)

You have to use: abs() for int fabs() for double fabsf() for float Above function will also work but you can also try something like this.
if(a<0)
{
a=-a;
}

Use float fabsf (float n) for float values.
Use double fabs (double n) for double values.
Use long double fabsl(long double) for long double values.
Use abs(int) for int values.

Well, in mathematics to convert a negative number to a positive number you just need to multiple the negative number by -1;
Then your solution could be like this:
a = a * -1;
or shorter:
a *= -1;

a *= (-1);
problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

floor a;
floor b;
a = -0.340515;
so what to do?
b = 65565 +a;
a = 65565 -b;
or
if(a < 0){
a = 65565-(65565+a);}

#include <iostream>
using namespace std;
int makePositiveSUM(int a,int b);
int main() {
int t;
cin>>t;
while(t--){
int x,y;
cin>>x>>y;
cout<<makePositiveSUM(x,y)<<endl;
}
return 0;
}
int makePositiveSUM(int a,int b){
if(a>b){
return a-b;
}
else {
return b-a;
}
}
enter code here
enter code here
enter code here

this is the only way i can think of doing it.
//positive to minus
int a = 5; // starting with 5 to become -5
int b = int a * 2; // b = 10
int c = a - b; // c = - 5;
std::cout << c << endl;
//outputs - 5
//minus to positive
int a = -5; starting with -5 to become 5
int b = a * 2;
// b = -10
int c = a + b
// c = 5
std::cout << c << endl;
//outputs 5
Function examples
int b = 0;
int c = 0;
int positiveToNegative (int a) {
int b = a * 2;
int c = a - b;
return c;
}
int negativeToPositive (int a) {
int b = a * 2;
int c = a + b;
return c;
}

Why do you want to use strange hard commands, when you can use:
if(a < 0)
a -= 2a;
The if statement obviously only applies when you aren't sure if the number will be positive or negative.
Otherwise you'll have to use this code:
a = abs(a) // a is an integer
a = fabs(a) // a is declared as a double
a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)
To activate C++ 11 (if you are using Code::Blocks, you have to:
Open up Code::Blocks (recommended version: 13.12).
Go to Settings -> Compiler.
Make sure that the compiler you use is GNU GCC Compiler.
Click Compiler Settings, and inside the tab opened click Compiler Flags
Scroll down until you find: Have g++ follow the C++ 11 ISO C++ language standard [-std=c++11]. Check that and then hit OK button.
Restart Code::Blocks and then you are good to go!
After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)

Related

How to use correctly struct type in c? [duplicate]

How do you divide two integers and get a double or float answer in C?
You need to cast one or the other to a float or double.
int x = 1;
int y = 3;
// Before
x / y; // (0!)
// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)
Of course, make sure that you are store the result of the division in a double or float! It doesn't do you any good if you store the result in another int.
Regarding #Chad's comment ("[tailsPerField setIntValue:tailsPer]"):
Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.
For example, on my system, the file:
#include <stdio.h>
int main()
{
double x = 3.14;
printf("%d", x);
return 0;
}
outputs:
1374389535
because the double was attempted to be read as an int.
Use type-casting.
For example,
main()
{
float a;
int b = 2, c = 3;
a = (float) b / (float) c; // This is type-casting
printf("%f", a);
}

How would I produce an integer from a float in the sense of removing the decimal point, despite floating-point precision errors?

In C, how can I produce, for example 314159 from 3.14159 or 11 from 1.1 floats? I may not use #include at all, and I am not allowed to use library functions. It must be completely cross platform, and fit in a single function.
I tried this:
while (Number-(int)Number) {
Number *= 10;
}
and this:
Number *= 10e6;
and floating-point precision errors get in my way. How can I do this? How can I accurately transform all digits in a float into an integer?
In response to a comment, they are a float argument to a function:
char *FloatToString(char *Dest, float Number, register unsigned char Base) {
if (Base < 2 || Base > 36 || !Dest) {
return (char *)0;
}
char *const RDest = Dest;
if (Number < 0) {
Number = -Number;
*Dest = '-';
Dest++;
}
register unsigned char WholeDigits = 1;
for (register unsigned int T = (int)Number/Base; T; T /= Base) {
WholeDigits++;
}
Dest[WholeDigits] = '.';
// I need to now effectively "delete" the decimal point to further process it. Don't answer how to convert a float to a string, answer the title.
return RDest;
}
The essential problem you have is that floating point numbers can't represent your example numbers, so your input is always going to be slightly different. So if you accurately produce output, it will be different from what you expect as the input numbers are different from what you think they are.
If you don't have to worry about very large numbers, you can do this most easily by converting to a long:
v = v - (long)v; // remove the integer part
int frac = (int)(v * 100000);
will give you the 5 digits after the decimal point. The problem with this is that it give undefined behavior if the initial value is too large to be converted to a long. You might also want to be rounding differently (converting to int truncates towards zero) -- if you want the closest value rather than the leading 5 digits of the fraction, you can use (int)(v * 100000 + (v > 0 ? 0.5 : -0.5))
New version :
#include <stdio.h>
int main()
{
double x;
int i;
char s[10];
x = 9999.12504;
x = (x-(int)x);
sprintf(s,"%0.5g\n",x);
sscanf((s+2),"%d",&i);
printf("%d",i);
return 0;
}
Old version
#include <stdio.h>
int main()
{
float x;
int i;
x = -3.14159;
x = (x-(int)x);
if (x>=0)
i = 100000*x;
else
i = -100000*x;
printf("%d",i);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void) {
double t = 0.12;
unsigned long x = 0;
t = (t<0)? -t : t; // To handle negative numbers.
for(t = t-(int)t; x < ULONG_MAX/10; t = 10*t-(int)(10*t))
{
x = 10*x+(int)(10*t);
}
printf("%lu\n", x);
return 0;
}
Output:
11999999999999999644
I feel like you should use modulo to get the decimal portion, convert it to a string, count the number of characters, and use that to multiply your remainder before casting it to an int.

How do I process the return value inf

I working through a book on C on my own. This isn't homework to be turned in. I am writing a C program to determine the largest Fibonacci number my machine can produce. And instructed to use a nonrecursive method.
My Code:
#include<stdio.h>
double fibo(int n);
int main(void)
{
int n = 0; // The number input by the user
double value; // Value of the series for the number input
while (n >= 0)
{
// Call fibo function
value = fibo(n);
// Output the value
printf("For %d the value of the fibonacci series = %.0f\n", n,
value);
n++;
}
return 0;
}
double fibo(int n)
{
int i; // For loop control variable
double one = 0; // First term
double two = 1; // Second term
double sum = 0; // placeholder
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
{
for (i = 2; i <= n; i++)
{
sum = one + two;
one = two;
two = sum;
}
}
return sum;
Code works fine but I want to to break when the output gives me the fist instance of :
For 17127 the value of the fibonacci series = inf
Is there way to us an if statement like:
if (value == inf)
break;
The simplest is to use INFINITY or isinf().
Just did a little search and found this nice trick:
...
double value, temp; // Value of the series for the number input
while (n >= 0)
{
// Call fibo function
temp = fibo(n);
if (temp - temp != 0)
break;
else
value=temp;
...
well it turns out that whats happening is when temp hits Inf the if condition temp - temp produces Nan which equals nothing and the rest is just executing break; to exit the process.
I want to to break when the output gives me the first instance of : inf
Simply test against INFINITY from <math.h>. The output will not be an exact Fibonacci number.
#include <math.h>
#include <stdio.h>
int main(void) {
double a;
double b = 0;
double c = 1;
do {
a = b;
b = c;
c = a + b;
} while (c < INFINITY);
printf("%e\n", b);
return 0;
}
Output
1.306989e+308
long double
Use the widest floating point type and look for an inexact addition.
#include <fenv.h>
#include <stdio.h>
int main(void) {
long double a;
long double b = 0;
long double c = 1;
do {
a = b;
b = c;
c = a + b;
} while (fetestexcept(FE_INEXACT) == 0);
printf("%.0Lf\n", b);
return 0;
}
Output
12200160415121876738
Integers
Use the widest type available. This is akin to #Syed.Waris unsigned long long approach. Although common that unsigned long long and uintmax_t have the same range, using uintmax_t insures the widest.
uintmax_t: The following type designates an unsigned integer type capable of representing any value of any unsigned integer type:
#include <stdint.h>
#include <stdio.h>
uintmax_t a;
uintmax_t b = 0;
uintmax_t c = 1;
do {
a = b;
b = c;
c = a + b;
} while(c >= b);
printf("%ju\n", b);
Output
12200160415121876738
String
An alternative to double or some int type, is to create a simple string add function str_add(), then quite easy to form large Fibonacci numbers.
int main(void) {
char fib[3][4000];
strcpy(fib[0], "0");
strcpy(fib[1], "1");
int i;
for (i = 2; i <= 17127 && strlen(fib[1]) < sizeof fib[1] - 1; i++) {
printf("Fib(%3d) %s.\n", i, str_add(fib[2], fib[1], fib[0]));
strcpy(fib[0], fib[1]);
strcpy(fib[1], fib[2]);
}
printf("%zu\n", strlen(fib[2]));
return 0;
}
Output
Fib(1476) 13069...(299 digits)....71632. // Exact max `double`
Fib(17127) 95902...(3569 digits)...90818.
largest Fibonacci number my machine can produce
This question is not concerned with any data type but it is concerned with machine.
The basic rule of fibonacci is this:
n = (n-1) + (n-2)
You can take a big sized unsigned long long variable and you can keep on adding. But what if that datatype is overflowed? You are not concerned with data type. Your machine may produce a number even bigger than the long long. What would that number be ? Entire bits on RAM? Hard Disk ?
Since you are required to use an iterative method and not recursive method, your teacher/book/instructor might be testing you on loops (and not any standard API). Below is sample code using unsigned long long:
#include <stdio.h>
int main ()
{
unsigned long long a = 0;
unsigned long long b = 1;
unsigned long long c = a + b;
while(c >= b)
{
a = c;
c = b + c;
b = a;
}
printf("\n%llu\n", b);
return 0;
}
Output:
12200160415121876738

How to concatenate two integer variables and make a float variable?

I have two integer variables and the result has to get stored in a float. I wanted to concatenate two integer variables and store them as a floating value. Let me know a method of joing two integer values.
Example.
I HAVE BELOW FUNCTION CALL. WHERE I AM STORING THE VALUE RECEIVED FROM KEY TO VARIABLE lat_int AND lat_float. i WANTED TO COMBINE BOTH AND STORE IN LATITUDE , WHICH IS GLOBALLY DECLARED AS FLOAT VALUE.
void setCustomCoordinate(int cord_para[])
{
lat_int=cord_para[0];
lat_float=cord_para[1];
long_int=cord_para[2];
long_float=cord_para[3];
latitude=(lat_int+lat_float)/100);
longitude=(long_int+long_float)/100));
}
this is not really a code question, but more a basic arithmetics question:
how do I transform two values so a and b give a.b?
simply by using addition and multiplication:
int a=10;
int b=20;
float r=0;
r = a+(b/100f);
thre's no need for an operator to do that (it takes two CPU instructions to calculate this value, calling a function would be more expensive) ; and it's not called "concatenation", but addition and multiplication (again).
If you want a concatenation, you should instead have "10" and "20" be strings that you concatenate using a dot, as an example, this is a string concatenation:
printf("%s.%s", "10", "20");
Use
math.h
int nDigits = floor(log10(abs(the_integer))) + 1;
then you can get a power of 10:
int power = pow(10,nDigits);
and finally:
float result = a + b / power;
No extra library file (such as math.h) is needed, the concat function can be created like this ...
float concat(int a, int b){
float c;
c = (float)b;
while( c > 1.0f ) c *= 0.1f; //moving the decimal point (.) to left most
c = (float)a + c;
return c;
}
You can convert this integer values to float.
For example consider 10 as 10.00 and 20 as 00.20
Then perform addition operation a+b which will give you outpout as 10.20
You can just divide b by 10^p where p is its string length then add a to b
example
if a is 1000 and b is 323 so b length = 3
so you will divide b by 1000 it will be 0.323 and then just add a to b
If you really just want to concatenate two integers, you could use c++ stringstream's to accomplish that, something like:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int a = 4;
int b = 5;
ostringstream oss;
oss << a << "." << b;
istringstream iss(oss.str());
float c;
iss >> c;
cout << c << endl;
return 0;
}
Output: 4.5
Ideone example
You could also use the combination of printf() and strtof():
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
int a = 10;
int b = 20;
float f;
char *buf;
if (asprintf(&buf, "%d.%d", a, b) > 0) {
f = strtof(buf, NULL);
printf("%f\n", f);
free(buf);
}
exit(EXIT_SUCCESS);
}

How to get fractions in an integer division?

How do you divide two integers and get a double or float answer in C?
You need to cast one or the other to a float or double.
int x = 1;
int y = 3;
// Before
x / y; // (0!)
// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)
Of course, make sure that you are store the result of the division in a double or float! It doesn't do you any good if you store the result in another int.
Regarding #Chad's comment ("[tailsPerField setIntValue:tailsPer]"):
Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.
For example, on my system, the file:
#include <stdio.h>
int main()
{
double x = 3.14;
printf("%d", x);
return 0;
}
outputs:
1374389535
because the double was attempted to be read as an int.
Use type-casting.
For example,
main()
{
float a;
int b = 2, c = 3;
a = (float) b / (float) c; // This is type-casting
printf("%f", a);
}

Resources