I know that this may be a dumb question, but I am still learning C so I don't know all the nuances.
Basically the gist of my question is that say I have the separate integers 1, 3 and 2. I want to add 2 to 1 that makes it 21. I know I could do 2*10, then add 1. Then add 3 to the beginning making it 321. Basically I need to add one number to the beginning of another number multiple times. Sadly, I cannot use the pow function for this.
Let me know if you need me to explain it anymore.
CodePudding user response:
There is many ways you can do this.
If you can't use the pow function why not make your own?
Here is one way I thought of doing this. I hope this can inspire you to come up with your own way.
If you need more then 10 digits you would have to use long instead of int.
#include <stdio.h>
int notpow(int y) {
int ans = 10;
if (y == 0) {
return 1;
}
for (int i = 1; i < y; i ) {
ans *= 10;
}
return ans;
}
int main() {
// //Basic idea
int num1 = 1;
int num2 = 3;
int num3 = 2;
int ans = 0;
ans = num1*notpow(2) num2 *notpow(1) num3*notpow(0);
printf("ans = %i\n", ans);
//For n numbers
int howMany, howManyCount = 1;
printf("How many digits?: ");
scanf("%d",&howMany);
int temp = 0;
int countDown = howMany-1;
ans = 0;
printf("\n");
for (int i = 0; i < howMany; i ) {
printf("Enter digit %i: ", (i 1));
scanf("%d",&temp);
printf("\n");
ans = ans temp*notpow(countDown--);
printf("ans = %i\n", ans);
}
printf("Final ans = %i\n", ans);
return 0;
}
CodePudding user response:
Well, you can try out this program.
#include <stdio.h>
#include <string.h>
int power(int base, int exp) {
int res = 1;
while (exp > 0) {
res *= base;
exp--;
}
return res;
}
int main() {
int someNumber = 7, length, numToAdd = 3;
char string[10];
sprintf(string, "%d", someNumber);
length = strlen(string);
someNumber = numToAdd * power(10, length) someNumber;
printf("%d\n", someNumber);
}
I hope the code is self explanatory.