This question already has answers here:
Division in c not giving expected value
(4 answers)
Closed 29 days ago.
I was making a code that adds a summation for a specific formula, but the sum is always 0 for some reason. What is the reason nothing is adding? I think maybe it is the declaration of int and double for the variables. When I do a simple equation, such as adding natural numbers, it works, but not for more complicated equations like the one below.
Code:
#include <stdio.h>
int main()
{
int i, n;
double sum = 0;
printf("Enter the max value for the sum: ");
scanf("%d", &n);
i = 1;
while(i <= n)
{
sum = sum + (1 / ((1 + i) * (1 + i)));
i++;
}
printf("Sum = %f\n", sum);
}
I tried the code pasted above, expected the correct sum, but resulted in only 0.0000.
In this statement
sum = sum + (1 / ((1 + i) * (1 + i)));
the sub-expression (1 / ((1 + i) * (1 + i))) uses the integer arithmetic. It means that if to divide 1 by any integer number greater than 1 the result will be equal to 0.
Consider this simple demonstration program
#include <stdio.h>
int main( void )
{
int i = 1;
i = i / 2;
printf( "i = %d\n", i );
}
Its output is
i = 0
You need to use the arithmetic with float numbers.
It will be enough to write
sum += 1.0 / ((1 + i) * (1 + i));
Or it will be even more better to write using long long int constant 1ll within the expression like
sum += 1.0 / ((1ll + i) * (1ll + i));
to avoid overflow for the integer multiplication.
Also as the range is specified as two positive numbers then it will be logically better to specify the variables i and n as having the type unsigned int.
You need to cast the result of the divison as a double since that is what you are expecting as a result. Int division will round it to closest whole number
Related
The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.
I tried to make a C program that checks if a bank card is valid.
According to Luhn’s algorithm, you can determine if a credit card number is (syntactically) valid as follows:
Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products' digits together.
Add the sum to the sum of the digits that weren’t multiplied by 2.
If the total’s last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!
That’s kind of confusing, so let’s try an example with my AmEx: 378282246310005.
For the sake of discussion, let’s first underline every other digit, starting with the number’s second-to-last digit:
378282246310005
Okay, let’s multiply each of the underlined digits by 2:
7•2 + 2•2 + 2•2 + 4•2 + 3•2 + 0•2 + 0•2
That gives us:
14 + 4 + 4 + 8 + 6 + 0 + 0
Now let’s add those products' digits (i.e., not the products themselves) together:
1 + 4 + 4 + 4 + 8 + 6 + 0 + 0 = 27
Now let’s add that sum (27) to the sum of the digits that weren’t multiplied by 2:
27 + 3 + 8 + 8 + 2 + 6 + 1 + 0 + 5 = 60
Yup, the last digit in that sum (60) is a 0, so my card is legit!
So, validating credit card numbers isn’t hard, but it does get a bit tedious by hand
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int length(long long n);
int num_at(int x,long long y);
long long flip(double a);
int main(void)
{
//int total2=0;
//printf("Number: ");
//int i=get_int();
long long ll=get_long_long();
//if (ll<=0)
//{
// printf("INVALID\n");
//}
//for (int i=1;2*i<length(ll);i++)
//{
// total2=total2+2*num_at(i,ll);
//}
//int total1=0;
//for (int i=0;2*i<length(ll);i++)
//{
// total1=total1+num_at(i,ll);
//}
//int total=total1+total2;
//printf("%i\n",total);
printf("%lli\n",flip(ll));
}
int length(long long n)/* length of number */
{
long long x=1;
int len=0;
while(n-n%x!=0)/* x % y means x mod y*/
{
len++;
x=x*10;
}
return len;
}
int num_at(int x,long long y)/* digit at specific spot in number */
{
int digit=0;//the digit at position z(see below)
int z=1;
for(z=x;z>=0;z--)
{
digit=y%10;
y=y-y%10;
y=y/10;
}
return digit;
}
long long flip(double a)//flips a
{
long long b=0;
for(int y=0;y<length(a);y++)
{
b=b*10;
b=b+(a%pow(10.0,y+1)-a%pow(10.0,y))/pow(10.0,y);
}
return b;
}
The error when compiling is:
credit.c:99:15: error: invalid operands to binary expression ('double' and 'double')
b=b+(a%pow(10.0,y+1)-a%pow(10.0,y))/pow(10.0,y);
~^~~~~~~~~~~~~~
credit.c:99:31: error: invalid operands to binary expression ('double' and 'double')
b=b+(a%pow(10.0,y+1)-a%pow(10.0,y))/pow(10.0,y);
~^~~~~~~~~~~~
You cannot perform the modulus operation on double(or floats).
This is for the simple reason that remainders are defined only for integer arithmetic. What would be the remainder if I divide 2.3 by 0.4??
So to do what you want you need to cast the double ( a and the result of pow) as long long.
So you can do ((long long) a) % (long long) pow( ... ) and it should be fine.
In the future you should look at the error messages (and also the warnings).
Here it clearly says invalid operands to binary expression and % operator is marked.
pow returns a double and % operator is defined only for integers. I think that should solve your problem.
Algo should be more simple that you write it.
I'm not a C programmer but:
// transform LL to char []
int len = length(ll);
char card[len];
sprintf(card, "%lld", ll);
int sum =0;
for(i=0;i < len; i++)
{
int num = card[i] - '0';
if(i % 2 == 0)
{ sum += num; }
else
{
int tmp = num * 2;
sum += (tmp / 10);
sum += (tmp % 10);
}
}
if(sum % 10)
{
// card valid
}
Is more readable in my opinion.
(Sorry if typo, this post was written with an old smartphone...)
EDIT
I know you like using loops but your num_at could also be enhanced :
int num_at(int pos, long long x)
{
return (x / (int)pow(10, pos)) % 10;
}
How do you expect to do a modulo operation (%) between two double values?
What is 10.3 % 5.2, exactly?
The error message is simply saying, "You cannot do double-modulo-double"
Is there any way to round systemGuess up. In this case the outcome of systemGuess is 5.5 I want it to be 6 how do I do this?
See code below:
int main(void){
int systemGuess = 0;
stystemGuess = (10 - 1)/2 + 1;
printf(" %d ", stystemmGuess);
}
Use floating point division and ceil:
stystemGuess = ceil((10 - 1)/2.0) + 1;
If you want to round 0.4 down, use round instead.
OP wants to perform an integer division with the result rounded-up.
// If the quotient fraction > 0, return next larger number.
unsigned udiv_ceiling(unsigned n, unsigned d) {
return (n + d - 1)/d;
}
// If the quotient fraction >= 0.5, return next larger number.
unsigned udiv_nearest_ties_up(unsigned n, unsigned d) {
return (n + d/2)/d;
}
stystemGuess = udiv_ceiling(10 - 1, 2) + 1;
// or
stystemGuess = udiv_nearest_ties_up(10 - 1, 2) + 1;
Additional code needed to handle negative numbers and in corner cases, protect against n + d - 1 overflow.
You can use
systemGuess = (10 - 1)/2.0 + 1 + 0.5;
The problem is that you do integer calculation.
So e.g. 9/2 is 4. If you use 9/2.0 you have floating point division, which gives you 4.5. Adding 0.5 in the end gives you 6.0 instead of 5.5, so when storing it in systemGuess, you get 6 instead of 5.
Integer division in C truncates toward 0, so if you do the math on the other side of 0 (i.e., on negative numbers), it will "round up". You might do this by subtracting an amount from the dividend and adding half that amount back to the result:
int main(void)
{
int systemGuess = 0;
//systemGuess = (10 - 1)/2 + 1;
systemGuess = (10 - 1 - 20)/2 + 1 + 10;
printf(" %d ", systemGuess);
}
Probably in your real program there is a more elegant way to make this happen.
Here you go:
#include <stdio.h>
#include <stdlib.h>
int divide(int x, int y);
int main(void){
int systemGuess = 0;
int x = 10-1;
int y = 2;
systemGuess = divide(x,y) + 1;
printf(" %d ", systemGuess);
}
int divide(int x, int y) {
int a = (x -1)/y +1;
return a;
}
i have the recurrence relation of
and the initials condition is
a0 = a1 = 0
with these two, i have to find the bit strings of length 7 contain two consecutive 0 which i already solve.
example:
a2 = a2-1 + a2-2 + 22-2
= a1 + a0 + 20
= 0 + 0 + 1
= 1
and so on until a7.
the problem is how to convert these into c?
im not really good at c but i try it like this.
#include<stdio.h>
#include <math.h>
int main()
{
int a[7];
int total = 0;
printf("the initial condition is a0 = a1 = 0\n\n");
// a[0] = 0;
// a[1] = 0;
for (int i=2; i<=7; i++)
{
if(a[0] && a[1])
a[i] = 0;
else
total = (a[i-1]) + (a[i-2]) + (2 * pow((i-2),i));
printf("a%d = a(%d-1) + a(%d-2) + 2(%d-2)\n",i,i,i,i);
printf("a%d = %d\n\n",i,total);
}
}
the output are not the same as i calculate pls help :(
int func (int n)
{
if (n==0 || n==1)
return 0;
if (n==2)
return 1;
return func(n-1) + func(n-2) + pow(2,(n-2));
}
#include<stdio.h>
#include <math.h>
int main()
{
return func(7);
}
First of uncomment the lines which initialized the 2 first elements. Then at the for loop the only 2 lines need are:
a[i]=a[i-1]+a[i-2]+pow(2, i-2);
And then print a i
In the pow() function, pow(x,y) = x^y (which operates on doubles and returns double). The C code in your example is thus doing 2.0*(((double)i-2.0)^(double)i)... A simpler approach to 2^(i-2) (in integer math) is to use the bitwise shift operation:
total = a[i-1] + a[i-2] + (1 << i-2);
(Note: For ANSI C operator precedence consult an internet search engine of your choice.)
If your intention is to make the function capable of supporting floating point, then the pow() function would be appropriate... but the types of the variables would need to change accordingly.
For integer math, you may wish to consider using a long or long long type so that you have less risk of running out of headroom in the type.
This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
Im trying to sum the multiples of a number (x0) with a progression number (r) and a number of times (n). If I use the number x0 = 6, r = 3, n = 3, the result should be
6+9+12=27, but the program gives me always 18.
I try different times changing the formula but if I do on the paper the result is right, so Im afraid the problem can be the syntax...
So theres the program in C:
#include <stdio.h>
int sum_progression(int x0, int r, int n)
{
return (n/2) * ((2 * x0) + ((n - 1) * (r)));
}
void test_sum_progression(void)
{
int x0;
int r;
int n;
scanf("%d", &x0);
scanf("%d", &r);
scanf("%d", &n);
int z = sum_progression(x0,r,n);
printf("%d\n", z);
}
int main(void)
{
test_sum_progression();
return 0;
}
Thanks for helping!
When using ints with division the value is calculated and then truncated to int.
if you divide int by int you should do something like:
return (n/(double)2) * ((2 * x0) + ((n - 1) * (r)));