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);
}
Related
I am a beginner in C
I am facing some problem with this code below:-
Code
#include <stdio.h>
int main()
{
int a = 7, b;
b = a * 0.621;
printf("%f", (float)b);
return 0;
}
The output was supposed to be 4.347 but, here, the output is 4.000000.
What should I do to get 4.347 instead of 4.000000?
'b' is of int type, so it will store only 4 and since you are using (float) in print, it will display the value 4 as 4.000000. Change data type of b to float or double.
int a=7,b;
should be changed to
int a=7;float b;
You need to change the int type to double type , Which can contain a decimal number.
int main()
{
double a=7 , b;
b = a*0.621;
printf("%f",(b));
return 0;
}
Out put : 4.34700
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.
I need to convert my float (sensor) value to a char array for sending my data through GPRS. If I use any library function for converting, it takes a lot of memory, because the controller has less amount of flash. I have tried my best to convert the data without a library function, but finally it needs the math.h file compulsorily. How can I solve this issue without any library function?
#include <stdio.h>
#include <string.h>
#include <math.h>
unsigned char str[20];
unsigned char *ftos(float f,int precision)
{
memset(str,0,sizeof(str));
float ff;
ff = f;
int a,b,c,k,l=0,m,i=0;
// check for negetive float
if(f<0.0)
{
str[i++]='-';
f*=-1;
}
a=f; // extracting whole number
f-=a; // extracting decimal part
k = precision;
// number of digits in whole number
while(k>0)
{
l = pow(10,k);
m = a/l;
if(m>0)
{
break;
}
k--;
}
// number of digits in whole number are k+1
/*
extracting most significant digit i.e. right most digit , and concatenating to string
obtained as quotient by dividing number by 10^k where k = (number of digit -1)
*/
for(l=k+1;l>0;l--)
{
b = pow(10,l-1);
c = a/b;
str[i++]=c+48;
a%=b;
}
str[i++] = '.';
/* extracting decimal digits till precision */
for(l=0;l<precision;l++)
{
f*=10.0;
b = f;
str[i++]=b+48;
f-=b;
}
str[i]='\0';
return str;
}
int main()
{
float temp = 35.2;
printf("%s",ftos(temp,2));
}
Don't try to print a floating point value, print a fixed point value instead. For example, this prints value of x with 2 digits after the decimal point:
int main()
{
float x = 35.2;
printf("%d.%02d\n", (int)x, (int)(x * 100) - (int)x * 100);
}
If you need to actually convert the value to a char array, use sprintf instead of printf. Be careful to avoid integer overflows when multiplying, especially if your platform has 16-bit integers: use long values if required.
Overall, there are very few cases when printing floating point numbers is a good idea from a microcontroller C code.
Im trying to make a program that calculates out a math equation, Im getting stuck on how i generate a random number from 0.00 to 1.00 and store it in a variable a.
this is my code so far, im stuck to how now take that number and store it for future use. I need to store that random number in a, and hten use it in a loop, and then generate a new random number and use it in the 2nd cycle of the loop.
EDIT
this is what i have been working on now, it is suppose to calculate the number of times a random number is inside the area, count it, and then devide by the number of times run, but im not getting any output
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));
while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
}
printf("%f", calculatedpi);
}
There are a few issues with your code:
You shouldn't use nested functions. Some compilers support them as an extension but it's not standard. Define randfloat and initrand outside main
The function initrand does too little. Why not call srand((time(0)); from main ?
Your initrand function is declared as returning a double but it doesn't return anything (and the way it's named it shouldn't). If you need to use such a function, why not make it return void ?
You should rarely use float. Why not use double ?
That said, you can do this to store that random value:
double randdouble()
{
return rand()/((double)RAND_MAX + 1);
}
int main()
{
double x = randdouble();
/* ... */
}
I think you want something like this:
#include <stdlib.h>
#include <time.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
initrand();
float a = randfloat();
return 0;
}
You can't nest functions like in some other languages.
You had non-matching parentheses in the initrand function.
I fixed the declarations of your functions, use void when there are no parameters, initrand doesn't return anything.
Your division by RAND_MAX+1 was a little messed up. Simply divide by RAND_MAX and the result will be in the closed interval [0,1]. And the syntax for the conversion to float was not quite right.
If you want to get random double numbers in a specified range you can use this function
// Return a random double from a to b
double randomDouble(double a, double b)
{
return = ( rand() / ( (double)RAND_MAX + 1.0))
* (b - a) + a;
}
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)