I am working on a project and I have an idea on how to start. Basically this is how the program runs:
$ ./rulerbuddy 2.25
2.25 is exactly 2 1/4
So, I kind of have the idea that I need first to rip off the whole number which in this case is '2' then start manipulating the fraction to get the result. My question is how can I rip off that whole number from the decimal fraction? Any ideas, steps, guide is appreciated. Thank you.
Take out the whole number and consider only the decimal part (do a sscanf(input, "%d.%d", &intPart, &fracPart) to take them apart).
Count the digits after the decimal point; your starting fraction is digits/10^number of digits, i.e. in your case 25/100;
Now you can simplify it finding the greatest common divisor (e.g. with Euclid algorithm) and dividing both terms by it.
Quick example of how this can be implemented:
#include <stdio.h>
#include <math.h>
struct Fraction
{
int n;
unsigned int d;
};
int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a-b*(a/b));
}
void simplify(struct Fraction * f)
{
int divisor=gcd(f->n, f->d);
f->n/=divisor;
f->d/=divisor;
}
int main(int argc, char * argv[])
{
int intPart;
unsigned int fracPart;
struct Fraction f;
if(argc<2)
{
puts("Not enough arguments.");
return 1;
}
if(sscanf(argv[1], "%d.%u", &intPart, &fracPart)!=2)
{
puts("Invalid input.");
return 2;
}
f.n=fracPart;
f.d=fracPart!=0?(int)pow(10., floor(log10(fracPart)+1)):1;
simplify(&f);
printf("%s is exactly: %d %d/%u\n", argv[1], intPart, f.n, f.d);
return 0;
}
if(num < 0)
num = num * (-1);
then
Just type cast the number explicitly to `int`
Use the standard library function floor
#include <math.h>
int WholeNumber(double number)
{
return (int)floor(number);
}
int main(void)
{
int N;
N = WholeNumber(2.25);
printf("The Whole part is %d\n", N); // this will print 2
}
Try a regex
http://rubular.com/r/KkE34B4ODQ
I've set that up to work for your example, you may need to alter it based on what your program provides for whole numbers (ie.e 2 0/1) or whatever.
The first group is the whole
second is numerator
third is denominator
Related
I am trying to reverse decimal numbers more efficient.
#include <stdio.h>
int main()
{
while(1)
{
int a,result;
scanf("%d",&a);
result=(a%10*10)+(a/10);
printf("%d\n",result);
}
}
Of course this will only work with 2 decimal numbers.
But I am trying to find out how I can reverse more numbers in an efficient way ( less code)
Sorry I need to be more specific. LESS CODE –
Ugly, but short code to "reverse" a number.
int main(){int c=getchar();if(isdigit(c))main();putchar(c);}
#include <stdio.h>
int main()
{
long in = 3456789;
long out = 0;
while(in)
{
out *= 10;
out += in % 10;
in /= 10;
}
printf("%ld\n",out);
return 0;
}
This way it will work for every type of number, no matter the number of digits, as long as it matches the data type.
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
int rev (int N);
int rev(int N){
return ((N <= 9)) ? N : rev(N / 10) + ((N % 10) * (pow(10, (floor(log10(abs(N))))))) ;
}
int main(void){
int r, n;
scanf("%d", &n);
r = rev(n);
printf("%d %d", r, n);
return EXIT_SUCCESS;
}
A simple code just to find out the reverse of a number. Everything is fine. Until I put a number with more than 2 digits. Things behave weirdly, somehow the last digit is always 0 of the reversed number. I have checked out in online compilers where things behave just fine. However the problem arises when I run the code on my own machine. I am on Windows 10 with MINGw. Could you guys suggest me a solution. I previously had problems where the value stored in an int matrix changes to huge values which is practically impossible to store in int due to it's size.
Using the pow and floor function, working with floats will not always round the way you'd expect.
As already commented, work with integers.
Propose doing this digit-by-digit, and sticking with integers. A proposal for your rev() function:
int rev(unsigned int N)
{
unsigned int res = 0;
while(N>0)
{
// pick off lowest digit
unsigned int digit = N%10;
// put into result, moving up all previous digits by doing *10
res = 10*res+digit;
// remove this digit from input value
N/=10;
}
return res;
}
This factorial function starts giving wrong results with 13 and above. I have no idea why.
#include <stdio.h>
int fatorial (int p);
int main() {
int x = 13;
int test = fatorial(x);
printf("%d", test);
}
int fatorial (int p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
for x = 0, 1, 2 ...12 it prints the right result, but for 13! it prints 1932053504 which is not correct.
For x=20 it prints -210213273 for example.
I know that this is not the best way to do a factorial. Its my homework tho, it HAS to be this way.
If you try this you will get the maximum value that int can hold:
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%d\n", INT_MAX);
}
Your code causes overflow.
You could get a few more numbers if you use a bigger type, but not by very much. You could use this:
unsigned long long fatorial (unsigned long long p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}
It won't get you far though. If you want bigger than that you need to find a library for bigger integers or create some custom solution. One such library is https://gmplib.org/ but that is likely out of scope for your homework.
And btw, a condition like p <= 0 is not good. It indicates that the factorial of a negative number is always one, which is false.
It is because after 12, the result of factorial of any number exceeds the size of int.
you can try the following code:
#include<stdio.h>
int main()
{
int a[100],n,counter,temp,i;
a[0]=1;
counter=0;
printf("Enter the number: ");
scanf("%d",&n);
for(; n>=2; n--)
{
temp=0;
for(i=0; i<=counter; i++)
{
temp=(a[i]*n)+temp;
a[i]=temp%10;
temp=temp/10;
}
while(temp>0)
{
a[++counter]=temp%10;
temp=temp/10;
}
}
for(i=counter; i>=0; i--)
printf("%d",a[i]);
return 0;
}
The result of the function is too big. I think big int would work better for your purposes. Big int allows you to have bigger numbers. Also, this is what I would do.
int x = the number you want to factorialize
int ans = 1;
(Then instead of all of those functions)
for(var i = x; i > 0; i--) {
ans = ans*i;
}
System.out.println(ans);
Javascript link: https://jsfiddle.net/8gxyj913/
I need to get to 100!
100! is about 9.332622e+157. Simply using standard integer types is insufficient. 32-bit int is good to 12!. With 64-bit integer math, code could get to about 21!
Could use floating point math and give up precision.
Instead consider a string approach.
I am a beginner starting in C and am doing some exercises on codewars. The exercise requires me to take a decimal int, convert it into binary and output the number of 1s in the binary number. Below my incomplete code. I store the binary in int b and I want to output it into an array so that I can run a loop to search for the 1s and output the sum.
Thanks in advance!
#include <stddef.h>
#include <stdio.h>
//size_t countBits(unsigned value);
int countBits(int d);
int main() {
int numD = 1234;
int numB = countBits(numD);
printf("The number %d converted to binary is %d \n", numD, numB);
}
int countBits(int d) {
if (d < 2) {
return d;
} else {
int b = countBits(d / 2) * 10 + d % 2; //convert decimal into binary
int c;
int bArray[c];
}
Your function is almost correct:
you should define the argument type as unsigned to avoid problems with negative numbers
you should just return b in the else branch. Trying to use base 10 as an intermediary representation is useless and would fail for numbers larger than 1023.
Here is a corrected version:
int countBits(unsigned d) {
if (d < 2) {
return d;
} else {
return countBits(d / 2) + d % 2;
}
}
There are many more efficient ways to compute the number of bits in a word.
Check Sean Eron Anderson's Bit Twiddling Hacks for classic and advanced solutions.
You can make an array char as one of the replies said, for example:
#include <stdio.h>
#include <string.h>
int main(){
int count=0;
int n,bit;
char binary[50];
printf("Enter a binary: \n");
scanf("%s",binary);
n=strlen(binary);
for(int i=0;i<n;i++){
bit=binary[i]-'0';
if (bit==1){
count=count+1;
}
}
printf("Number of 1's: %d\n",count);
return 0;
}
This should count the number of 1's of a given binary.
Try something like this!
edit: I know that binary[i]-'0' might be confusing, if you don't understand that..take a look at this:
There are definitely 'smarter'/more compact ways to do this, but here is one way that will allow you to count bits of a bit larger numbers
#include <stdio.h>
int count_bits(int x)
{
char c_bin[33];
int count=0;
int mask=1;
for( int i =0; i < 32; i++){
if (x & mask ){
count=i+1;
c_bin[31-i]='1';
}
else{
c_bin[31-i]='0';
}
mask=mask*2;
}
c_bin[32]='\0';
printf("%d has %d bits\n",x,count);
printf("Binary x:%s\n",c_bin);
return count;
}
int main()
{
int c=count_bits(4);
return 0;
}
I have a simple code to convert binary to decimal numbers. In my compiler, the decomposition works just fine for number less than 1000, beyond the output is always the same 1023. Anybody has an idea ?
#include <stdio.h>
#include <stdlib.h>
// how many power of ten is there in a number
// (I don't use the pow() function to avoid trouble with floating numbers)
int residu(int N)
{
int i=0;
while(N>=1){
N=N/10;
i++;
}
return i;
}
//exponentiating a number a by a number b
int power(int a, int b){
int i;
int res=1;
for (i=0;i<b;i++){res=a*res;}
return res;
}
//converting a number N
int main()
{
int i;
//the number to convert
int N;
scanf("%d",&N);
//the final decimal result
int res=0;
//we decompose N by descending powers of 10, and M is the rest
int M=0;
for(i=0;i<residu(N);i++){
// simple loop to look if there is a power of (residu(N)-1-i) in N,
// if yes we increment the binary decomposition by
// power(2,residu(N)-1-i)
if(M+ power(10,residu(N)-1-i) <= N)
{
M = M+power(10,residu(N)-1-i);
res=power(2,residu(N)-1-i)+res;
}
}
printf("%d\n",res);
}
Yes try this :
#include <stdio.h>
int main(void)
{
char bin; int dec = 0;
while (bin != '\n') {
scanf("%c",&bin);
if (bin == '1') dec = dec * 2 + 1;
else if (bin == '0') dec *= 2; }
printf("%d\n", dec);
return 0;
}
Most likely this is because you are using an int to store your binary number. An int will not store numbers above 2^31, which is 10 digits long, and 1023 is the largest number you can get with 10 binary digits.
It would be much easier for you to read your input number as a string, and then process each character of the string.
After a little experimentation, I think that your program is intended to accept a number consisting of 1's and 0's only as a base-10 number (the %d reads a decimal number). For example, given input 10, it outputs 2; given 1010, it outputs 10; given 10111001, it outputs 185.
So far, so good. Unfortunately, given 1234, it outputs 15, which is a little unexpected.
If you are running on a machine where int is a 32-bit signed value, then you can't enter a number with more than 10 digits, because you overflow the limit of a 32-bit int (which can handle ±2 billion, in round terms). The scanf() function doesn't handle overflows well.
You could help yourself by echoing your inputs; this is a standard debugging technique. Make sure the computer got the value you are expecting.
I'm not going to attempt to fix the code because I think you're going about the problem in completely the wrong way. (I'm not even sure whether it's best described as binary to decimal, or decimal to binary, or decimal to binary to decimal!) You would do better to read the input as a string of (up to 31) characters, then validate that each one is either a 0 or a 1. Assuming that's correct, then you can process the string very straight-forwardly to generate a value which can be formatted by printf() as a decimal.
Shift left is the same than multiply by 2 and is more efficient, so I think it is a more c-like answer:
#include <stdio.h>
#include <stdlib.h>
int bin2int(const char *bin)
{
int i, j;
j = sizeof(int)*8;
while ( (j--) && ((*bin=='0') || (*bin=='1')) ) {
i <<= 1;
if ( *bin=='1' ) i++;
bin++;
}
return i;
}
int main(void)
{
char* input = NULL;
size_t size = 0;
while ( getline(&input, &size, stdin) > 0 ) {
printf("%i\n", bin2int(input));
}
free(input);
}
#include <stdio.h> //printf
#include <string.h> //strlen
#include <stdint.h> //uintX_t or use int instead - depend on platform.
/* reverse string */
char *strrev(char *str){
int end = strlen(str)-1;
int start = 0;
while( start<end ){
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return str;
}
/* transform binary string to integer */
uint32_t binstr2int(char *bs){
uint32_t ret = 0;
uint32_t val = 1;
while(*bs){
if (*bs++ == '1') ret = ret + val;
val = val*2;
}
return ret;
}
int main(void){
char binstr[] = "1010101001010101110100010011111"; //1428875423
printf("Binary: %s, Int: %d\n", binstr, binstr2int(strrev(binstr)));
return 0;
}