Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've got multiple float numbers to print:
{3.00, 3.20, 2.23, 5.00, 3.40 }
They all have 2 decimal places, however if there are two zero's after a decimal, it needs to be displayed as a whole number.
How can I convert 3.00 into 3 and 5.00 into 5?
it is conversion not printing
There is no way to directly (i.e. using only the format specifier) print either two decimals or zero for a number ending in e.g. 3.20.
You need to check if the number ends with .00 beforehand; for example:
if((int)round(num * 100) % 100 == 0) // if decimals are `.00`
printf("%.0f", num);
else // not `.00`
printf("%.2f", num);
If 3.2 is okay for 3.20, then the %g specifier might also be of some use.
Just assign them to an int array or just type cast them in int for your purpose.
int i = 3.00; //lhs is int and rhs is double i will store 3 only
(int)3.00 //cast
printing them with %.f will also work
I think you cannot do this with a general format specifier or similar. You might need to treat each number separately and adjust the printf accordingly.
First you need to detect if you have digits that are 0.
You could do it like this
if (fabs(number - round(number)) < 0.01)
printf("%.2f", number);
else
printf("%d", (int) number);
This is just meant as a hint in the right direction. You might improve it a bit on your own.
Edit:
I assume that you want two digits for 3.20 and not 3.2 only.
Casting to integer type will truncate the positive integers down to integer part:
float f = 2.00;
printf("f: [%f], [%d]", f, (int) f);
f: [2.000000], [2]
If you want to leave 2.50 as 2.5 then checking for .00 is necessary:
if( (int) round(num * 100) % 100 == 0) // if decimals are .00
printf("%.0f", num); // truncate all
else // not .00
printf("%.2f", num); // truncate to 2 decimal places
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to write a C program to convert a number given a base, to any other base (Eg. base 2 binary number to base 8, or base 3 to base 16 hex). I've researched this quite a bit, and already read through a similar article, The math behind converting from any base to any base without going through base 10?] but in the explanation given, they utilize an array, which I am not allowed to do for this program.
Without writing a lengthy program with a method for each possible combination of base conversion, I don't see how this is possible without an array to store possible values. I do understand that there is a change of base formula with logs that allows me to change between number bases, but I am unclear how I would apply this, as this formula only gives a decimal number answer, which I would still need to convert.
int log_base_n(int n, int logof)
{
double logBaseN = log10((double) logof) / log10((double) n);
return (int) ceil(logBaseN);
}
Here is my binary to decimal conversion which I am trying to use as an intermediate step:
/**
* Convert decimal numbers to binary. Uses a greedy subtraction
* algorithm. Assumes max integer allowed is 2 to 16 power.
*
* #param numberToConvert
*/
void decToBin(int numberToConvert)
{
int power = 16;
double ans = pow(2, power);
if (numberToConvert > ans)
{
printf("ERROR: Number too large to convert!\n");
return;
}
while (ans > numberToConvert)
{
power--;
ans = pow(2, power);
}
printf("%d", 0);
int i = power;
while (i >= 0)
{
ans = pow(2, i);
numberToConvert = numberToConvert - ans;
printf("%d", 1);
i--;
while ((pow(2, i) > numberToConvert) && (i >= 0))
{
printf("%d", 0);
i--;
ans = pow(2, i);
}
}
}
I know Java has a parseInt() method, that does base conversions, but is there something similar I can implement in C without having to write methods for each possible conversion like the one above, while still utilizing a logarithm related idea? Any help would be greatly appreciated.
but is there something similar I can implement in C without having to write methods for each possible conversion like the one above, while still utilizing a logarithm related idea?
Logarithm is a poor choice. The computation of logs in code is not exactly the same as their mathematical counterpart and leads to incorrect output.
The below is a problem should the quotient result in a value just a little higher than a whole number expected value. Of course, log10() is a problem for logof <= 0.
double logBaseN = log10((double) logof) / log10((double) n);
return (int) ceil(logBaseN);
Further, the calculation of log_base_n() is quite unnecessary.
This is an integer problem. Use integer math.
A simply non-array solution "to convert from any base to another base"1 is to use recursion.
void print_int_base(int numberToConvert, int base) {
// For now, assume numberToConvert >= 0, 2 <= base <= 36
if (numberToConvert >= base) {
print_int_base(numberToConvert/base, base);
}
int digit = numberToConvert%base;
int c = digit < 10 ? digit + '0' : digit + 'A';
putchar(c);
}
Test code
#include <stdio.h>
void print_int_base_test(int numberToConvert, int base) {
printf("%10d %2d:", numberToConvert, base);
print_int_base(numberToConvert, base);
puts("");
}
int main() {
int numberToConvert = 42;
for (int base=2; base<=20; base++) {
print_int_base_test(numberToConvert, base);
}
}
Output
42 2:101010
42 3:1120
42 4:222
42 5:132
42 6:110
42 7:60
42 8:52
42 9:46
42 10:42
42 11:39
42 12:36
42 13:33
42 14:30
42 15:2M
42 16:2K
42 17:28
42 18:26
42 19:24
42 20:22
1 OP's idea of conversion apparently is to print the int in various bases.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
so i am having this strange problem here and I don't know what to do.
so in the following I am posting an excerpt of my code:
printf("%lf , %lf \n", cGrid_Y,sideLength);
printf("%lf <= %lf\n", Point_Y, cGrid_Y+sideLength);
bool x = (Point_Y <= (sideLength + cGrid_Y) );
printf("%s \n", x ? "true" : "false");
cGrid_Y and sideLength are doubles. And I am getting this output:
-12.800000 , 12.800000
0.000000 <= -0.000000
false
So my question is, why I am not getting a true ?
This is not a problem with negative zeros. 0.0 <= -0.0 is true. The problem is that your values are not actually zero or negative zero but some very small value that's being rounded to 0 for presentation when you ask printf to show it rounded to 6 decimal places. Either print with %e or %g (which will use exponential notation to show a better approximation) or %.1100f which is sufficient precision to show the exact value of any double.
So my question is, why I am not getting a true ?
Are you sure that Point_Y == 0.0? Same for the sum of sideLength + cGrid_Y?
Check your assumptions:
printf("Point_Y is zero: %d\n", Point_Y == 0.0);
printf("`sideLength + cGrid_Y` is zero: %d\n", (sideLength + cGrid_Y) == 0.0);
The reason you got confused is because by default printf's floats/doubles are't printed to full precision.
#include <stdio.h>
int main()
{
double x = 0.0000001;
printf("x: %f\n", x);
}
outputs: x: 0.000000
#edit I wrote a stupid mistaken thing: I thought that negative zero doesn't equal positive zero, whereas after reading it all properly -0 equals +0.
The source of your problem: you are trying to test whether two doubles are equal, and this is a terrible idea, due to the imprecision of floating point representation. Note the common example: 0.1 + 0.2 does NOT equal 0.3:
Is floating point math broken?
https://www.quora.com/Why-is-0-1+0-2-not-equal-to-0-3-in-most-programming-languages
You cannot represent 12.8 in binary without losing a part of the imformation, due to the fundamental nature of how this number is stored in the computer's memory.
The same way you can't represent 1/7 in our "normal" decimal representation of numbers with a finite amount of digits.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have been doing some research on the modf() function and I am having some trouble understanding on how to use it.
Code Example
#include<stdio.h>
#include<math.h>
int main ()
{
double x, fractpart, intpart;
x = 8.123456;
fractpart = modf(x, &intpart);
printf("Integral part = %lf\n", intpart);
printf("Fraction Part = %lf \n", fractpart);
return(0);
}
Confusion: The part I am getting confused on is the fractpart. I am having trouble understanding how it actually works because I only want to store the whole number part of a decimal number. Also, what is the point of the double.
First of, double is something really easy to understand. Float only stores seven digits, while a double stores between 15-16 digits. More detail here
Now for the modf. The modf in the fractpart =, it first checks x. Pretty much scanning it. After it does that, it stores everything before in the decimal point in inpart. After, what is remained is stored in fractpart which the decimal. To sum everything modf is like scanf. That is the reason why we put & before the intpart.
I only want to store the whole number part of a decimal number.
double modf(double value, double *iptr);
The modf functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. They store the integral part in the object pointed to by iptr. C11dr ยง7.12.6.12 1
Simplified code follows. No need for fractpart or even intpart. Simply store the whole number portion of x back into x
#include<stdio.h>
#include<math.h>
int main () {
double x = 8.123456;
modf(x, &x);
printf("Integral part = %f\n", x);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
say i have:
55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
i have been trying to use the round() function but it seems to keep giving me the highest value for all decimal places.
OP has not posted code that failed. Certain OP coded incorrectly.
Using round() is the correct way to round a double before converting to an int. Of course it must be in range.
#include <math.h>
#include <assert.h>
int round_to_int(double x) {
x = round(x);
assert(x >= INT_MIN);
assert(x < (INT_MAX/2 + 1)*2.0);
return (int) x;
}
See How to test for lossless double / integer conversion? for details about the assert()s.
Why not use (int)(x + 0.5);?
1) It fails for negative numbers.
2) It can fail for the double just smaller than 0.5 as the x + 0.5 can round to 1.0.
3) When the precision of int exceeds double, values where the least significant bit is 0.5 or 1.0, x+0.5 may round to the next integer.
4) Unadorned, it has no range checking.
In the olden days we used to say int the_int = (int)(some_double + 0.5); (obviously beware if you are dealing with negative values too).
Increase the magnitude by one half and truncate:
int round_up_or_down(double x)
{
return x > 0 ? x + 0.5 : x - 0.5;
}
This distributes the real intervals uniformly:
...
[-1.5, -0.5) => -1
[-0.5, +0.5) => 0
[+0.5, +1.5) -> +1
...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
for example length of 1.54 is 4 including the decimal point. i need a C code for finding the length in the same way but without strings and also snprintf
Calculating the length of a floating-point number decimal representation doesn't make much sense, as its underlying representation is binary. For example 0.1 in decimal form yields an infinite number of digits in binary.
C has no intrinsic decimal type, so you will have to represent your number with some ad-hoc type, and shave off insignificant digits on the right. C-strings are not the worse choice for that.
The length is set by you at the moment you print it.
#include <stdio.h>
int main ()
{
float x = 0.2;
double y = 0.2;
int size_x = sizeof(float);
int size_y = sizeof(double);
printf("Variable x has a size of %i. But i can print if as different lengths: %f, %3.2f, %g, %e\n", size_x, x, x, x, x);
printf("Variable y has a size of %i. But i can print if as different lengths: %lf, %3.2lf, %lg, %le\n", size_y, y, y, y, y);
return 0;
}