Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
need an programming logic to print an 4 decimal points
EX: scalar should be 0 to -5
value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
value = 123 ,scalar = -5 then print result = 0.0012 (4 decimals)**
required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )
I tried like this:
divisor = std::pow(10,std::abs(scalar));
**Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**
I'm not allowed to use float , setprecision() .
It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)
std::int32_t divisor = static_cast(std::pow( 10.0F, std::abs( Scalar)) );
but int the above result modulus scalar value with 0 are not considering.
**Please provide me the logic to print the above result with scalar condition
In order to print decimals (easily), you need floating point:
printf("%10.6f", static_cast<double>(1) / 3);
If one of the arguments to division is floating point, the compiler will promote the expression to floating point.
Integral or scalar division will lose decimals.
You are always welcome to write your own division function.
Edit 1: Shifting
You don't need to use the pow function (especially since it's floating point).
Use a loop, in the loop multiply your divisor by 10 each time.
double result = (double) scalar / value;
int divisor = 10;
int i;
for (i = 0; i < NUMBER_OF_DECIMALS; ++)
{
// Isolate a digit using math.
// print the digit
divisor += 10;
}
The math part is left as an exercise for the OP.
In this homework exercise you are expected to perform your own number formatting, rather than using that of a library.
For instance, to format and output 100 as "100"
int accum = 100;
int position = 0;
while (accum > 0)
{
printf("%d", accum % 10);
accum /= 10;
position += 1;
}
For your homework assignment, you need to modify the above loop so that it puts a printf(".") in the correct place in the output number. Your answer is likely to involve multiplying accum before the loop and testing position relative to scalar
Related
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 2 years ago.
Improve this question
Is there a way to convert a double into an integer without risking any undesired errors in the process? I read in Programming - Principles and Practice Using C++ (a book written by the creator of c++) that doubles cannot be turned into integers, but I've put it to the test, and it converts properly about 80% of the time. What's the best way to do this with no risk at all, if it's even possible?
So for example, this converts properly.
double bruh = 10.0;
int a = bruh;
cout << bruh << "\n";
But this doesn't.
double bruh = 10.9;
int a = bruh;
cout << bruh << "\n";
In short, it doesn't round automatically so I think that's what constitutes it as "unsafe".
It it not possible to convert all doubles to integers with no risk of losing data.
First, if the double contains a fractional part (42.9), that fractional part will be lost.
Second, doubles can hold a much larger range of values than most integers, something around 1.7e308, so when you get into the larger values you simply won't be able to store them into an integer.
way to convert a double into an integer without risking any undesired errors
in short, it doesn't round automatically so I think that's what constitutes it as "unsafe"
To convert to an integer value:
x = round(x);
To convert to an integer type:
Start with a round function like long lround(double x);. It "Returns the integer value that is nearest in value to x, with halfway cases rounded away from zero."
If the round result is outside the long range, problems occur and code may want to test for that first.
// Carefully form a double the is 1 more than LONG_MAX
#define LONG_MAXP1 ((LONG_MAX/2 + 1)*2.0)
long val = 0;
if (x - LONG_MAXP1 < -0.5 && x - LONG_MIN > -0.5) {
val = lround(x);
} else {
Handle_error();
}
Detail: in order to test if a double is in range to round to a long, it is important to test the endpoints carefully. The mathematical valid range is (LONG_MIN-0.5 ... LONG_MAX + 0.5), yet those endpoints may not be exactly representable as a double. Instead code uses nearby LONG_MIN and LONG_MAXP1 whose magnitudes are powers of 2 and easy to represent exactly as a double.
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 6 years ago.
Improve this question
I get a segmentation fault while assigning values to what looks to me a properly allocated array. Here is the code below:
int SpV = L*L*L;
int V = SpV*T;
int M = 16;
int Ns = 2;
int Np = 10;
float *twopBuf = (float*) malloc(Np*Ns*V*M*2*sizeof(float));
if(twopBuf == NULL){
fprintf(stderr,"Cannot allocate twopBuf. Exiting\n");
exit(-1);
}
for(int bar=0;bar<Np;bar++)
for(int pr=0;pr<Ns;pr++)
for(int t=0;t<T;t++)
for(int v=0;v<SpV;v++)
for(int gm=0;gm<M;gm++){
int pos = 2*gm + 2*M*v + 2*M*SpV*t + 2*M*SpV*T*pr + 2*M*SpV*T*Ns*bar;
twopBuf[ 0 + pos ] = 1.0; // Set to 1.0 for
twopBuf[ 1 + pos ] = 1.0; // testing purposes
}
L and T are input, so when say L = 32 and T = 64 it runs fine. But for L = 48 and T = 96 I get segmentation fault after bar becomes 2 and before it becomes 3. If there wasn't enough memory to allocate twopBuf wouldn't I already get the error message?
I'm running this on the head node of a large supercomputer, if it makes a difference. Thanks.
The expression
Np*Ns*V*M*2*sizeof(float)
is evaluated as
((((Np*Ns)*V)*M)*2)*sizeof(float)
due to the left-to-right associativity of * in C and C++. See C11 draft standard n1570, 6.5.5 Multiplicative operators.
The type of an expression E1 * E2 is the common real type of the operands (6.3.1.8 Usual arithmetic conversions). In this case, the types are
((((int*int)*int)*int)*int)*size_t
so all but the last multiplication is done at int-precision and range.
For L = 48, T = 96 and sizeof(float) == 4, the infinitely precise result of the int-precision multiplications is 6794772480, which is not representable in 16- or 32-bit int, so one of the multiplications must overflow on such an implementation, which is undefined behavior.
If the expression is reordered to:
sizeof(float)*Np*Ns*V*M*2
all of the multiplications are done at size_t precision, unless int can represent all values size_t can represent. If the multiplications are done at size_t-precision, the multiplication is well-defined even if it overflows, since size_t is unsigned. However, if it does overflow, malloc() will return an allocation that is significantly smaller than you expect, which causes undefined behavior if you access beyond the end of the allocated object.
For the numbers you have provided, 64-bit size_t will not overflow if size_t has less than 30 padding bits.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Question:
Your task is to:
Write a function that prints to the standard output (stdout) the number of users who didn't leave the site after 10 seconds (i.e: the number of users who didn't bounce).
Please round the result downwards to the nearest integer (e.g both 7.1 and 7.9 are rounded to 7).
Note that your function will receive the following arguments:
n which is an integer representing the number of visitors
b which is an integer representing the bounce rate (i.e: the percentage of users who left the site in the first 10 seconds)
My code compiles just fine and I am pretty sure that my logic is correct, but my output is wrong and I don't know why. When n = 1000 and b = 25 then my result should be 750. I keep on getting 1000. Where am I going wrong?
I am also not exactly sure how to "round down" the way that they want me to. Could that also be the reason why I am not getting the correct output?
MY CODE:
void compute_active_users(int n, int b) {
int BounceConvert = (b / 100); //converts the value of b to a decimal
int BounceRate = (n * BounceConvert); // multiplys n times the b decimal
int TotalVisitors = (n - BounceRate); // subtract BounceRate
printf("%d", TotalVisitors); // print out the final result
}
This uses the truncating behaviour of integer division in C for positive integers, which is the goal of your exercise:
void compute_active_users(int nbPeople, int bounceRate) {
int totalVisitors = nbPeople * (100 - bounceRate) / 100;
printf("%d\n", totalVisitors);
}
Your solution does not work because this line:
int BounceConvert = (b / 100);
will produce BounceConvert=0 (25/100 -> 0)
Consider b/100. In Integer division, when b=25, it boils down to 0, not 0.25 as you expect. For that use floating point operation.
void compute_active_users(int n, int b) {
float BounceRate = ((float)n * b)/100; // floating point operation
int roundedBounceRate = (int) BounceRate; //Integer cast rounds it lowest integer
int TotalVisitors = (n - roundedBounceRate); // subtract BounceRate
printf("%d", TotalVisitors); // print out the final result
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
How can I append an int to an int:
x = 23;
y = 54;
result = 2354;
I hope you help me.
Here are two general approaches:
"Shift" the left integer over by multiplying by the appropriate power of 10 and then add the right integer. In the example code that is x * 100 + y (or x * pow(10,2) + y) as shown in a comment.
The value to shift can be derived from the ceiling of the log10 of the right number. Using the math above, this could be expanded more generally as x * pow(10, ceil(log10(y))) + y.
Convert the integers to strings, concatenate the strings, and convert the resulting string back to an integer.
Take the inputs as a string
concatenate the strings. or you can use append to add the strings.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Working in C language, I would like to round a float number to its inferior odd integer and its inferior even integer.
The speed of the solution is very important (because it is computed 2M*20 times per seconds).
I propose this solution :
x_even = (int)floor(x_f) & ~1;
x_odd = ((int)ceil(x_f) & ~1) -1;
I presume that the weak point is the floor and ceil operations, but I'm not even sure of that.
Does someone have a comment on this solution ; I'm interested about it's speed of execution, but if you have another solution to share, I'll be very happy to test it :-).
You don't explain what you mean by 'inferior', but assuming you mean 'greatest even/odd integer less than the given number', and assuming you have a 2s-complement machine, you want:
x_i = (int)floor(x_f);
x_even = x_i & ~1;
x_odd = x_i - (~x_i & 1);
If you want to avoid the implementation dependency of doing bitwise ops on possibly negative signed numbers, you could instead do it entirely in float:
x_even = 2.0 * floor(x_f * 0.5);
x_odd = x_even + 1.0 > x_f ? x_even - 1.0 : x_even + 1.0;
This also has the advantage of not overflowing for large numbers, though it does give you x_odd == x_even for large numbers (those too big for the floating point representation to represent an odd number).
Perhaps the ceil and floor function won't be necessary as transtypage from a double to an int is equivalent to the floor function for positive integer.
Try something like this for POSITIVE INTEGERs :
double k = 68.8 ; // Because we need something to seed with.
int even = ((int) k & ~1) ; // What you did
int test = ((int) (k+1) & ~1) ; // Little trick
int odd = (test>k) ? odd+1 : odd - 1 ;
I tested it on codepad, and it works well for on http://codepad.org/y3t0KgwW for C++, I think it will in C. If you test this solution, I'd be glad to know how fast it can be...
Notice that :
This is not a good answer as it shadows the existence of negative integers.
The range is limited to integers'.
I swapped odd and even numbers, I corrected it thank's to Chris' comment.
I'm just adding my humble stone :)