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
I've written a program in C to convert Decimal numbers to Binary and store it in a string. The issue is not the binary that's printed in reverse but how the output is displayed
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%i", &decimal);
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
{
// considering binary is 64 bits in total
char bit[64];
int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
// update the dividend and counter
dividend /= 2;
++counter;
// break if dividend has reached 1
if(dividend == 1)
break;
} while(dividend);
// print the final result
printf("The binary equivalent of %i is %s\n", decimal, bit);
}
return(0);
}
The output of 2 (that should be 01 in reverse) gives something like this
$ 0The binary equivalent of 2 is 0time
for decimal 3
$ 1The binary equivalent of 3 is 1time
We beginners should help each other.:)
Here you are.
#include <stdio.h>
int main(void)
{
unsigned int decimal;
// get the decimal from user
printf("Enter the decimal number: ");
scanf("%u", &decimal);
// considering binary is 64 bits in total
char bit[64];
unsigned int dividend, remainder, counter;
// we need decimal value intact so dividend copies it
dividend = decimal;
counter = 0;
do
{
remainder = dividend % 2;
bit[counter++] = remainder + '0';
} while( dividend /= 2 );
bit[counter] = '\0';
// print the final result
printf("The binary equivalent of %u is %s\n", decimal, bit);
return 0;
}
The program output might look like
Enter the decimal number: 2
The binary equivalent of 2 is 01
As for your code then this code snippet
if(decimal == 1)
printf("The binary equivalent of %i is %i\n", decimal, decimal);
else
is redundant.
This code snippet
if(remainder != 0)
bit[counter] = putchar('1');
else
bit[counter] = putchar('0');
does not make sense. As it is shown in the demonstrative program above what you need is to write
bit[counter++] = remainder + '0';
This exit from the loop
if(dividend == 1)
break;
is wrong.
You also need to append the resulted string with a terminating zero.
Also as you do not take into account the sign of the entered number then it is better to declare it as having type unsigned int.
Take into account that headers <string.h> and <stdlib.h> are redundant and may be removed.
You need to change
if(dividend == 1)
to
if(dividend == 0)
Also memset bit to 0 prior to using it ie memset(bit,'\0',sizeof(bit)); before the loop
Related
I'm writing a program that takes in your student number(8 digits long), prints each digit on its own new line, and then gets the sum of all the digits in the number
(E.g. Student Number - 20305324, Sum - 19)
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[8];
int i = 0;
int sum = 0;
printf("Enter your student number: ");
scanf("%s", student_number);
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
scanf("%s", student_number);
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print - DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + student_number[i];
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
OUTPUT
The problem I'm encountering is when my for loop attempts to add each digit in the student number. The output I expect here is 19, but for some reason the sum evaluates to some bizarre number like 403
}
Would someone mind pointing out where exactly the fault in my for loop is or if it is elsewhere? Thanks :)
Firstly, your array char student_number[8]; cannot hold 8-character string because there are no room for terminating null character. You must allocate one more element.
Then, you should convert the characters to corresponding numbers. Character codes for digits are defined to be continuous, so this can be done by subtracting '0' from the character code.
Also you should set a limit of length of string to read via scanf() to avoid buffer overrun. One more good practice is checking the return values of scanf() to see if something is successfully read.
Fixed code:
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[10]; // *** allocate enough elements (one more than needed to catch too long input)
int i = 0;
int sum = 0;
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print -DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + (student_number[i] - '0'); // *** convert characters to numbers before adding
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
When you read characters as a string, the values of the char objects are codes for the characters. Your C implementation is likely using ASCII codes, in which 48 is the code for “0”, 49 is the code for “1”, 65 is the code for “A”, and so on.
To convert a code x for a digit to the value of the digit, use x - '0'.
I think that the task was to read the number not the string.
void printDigitsAndSum(unsigned number)
{
unsigned mask = 1;
unsigned sum = 0;
while(number / (mask * 10)) mask *= 10;
while(mask)
{
printf("%u\n", number / mask);
sum += number / mask;
number %= mask;
mask /= 10;
}
printf("Sum: %u\n", sum);
}
int main(void)
{
unsigned number;
if(scanf("%u", &number) == 1)
printDigitsAndSum(number);
else printf("Wrong number\n");
}
https://godbolt.org/z/1edceh
I have to do a program to take a number and print all the digits one by one as characters.
The code I have written is here:
#include <stdio.h>
#include <stdlib.h>
char digito(int, int);
int numberofdigits(int);
int main(void)
{
int num=0, test=0, kdigits=0, k=0;
char ch='\0';
printf("Enter a positive number:\n");
test=scanf("%d", &num);
if (teste!=1 || num<=0)
{
printf("Error: not a valid number.\n");
exit(EXIT_FAILURE);
}
kdigits = numberofdigits(num);
for(k=0; k<kdigits; k++)
{
ch= digito(num, k);
printf("The digit %d of the number is %c\n", k, ch);
}
return EXIT_SUCCESS;
}
int numberofdigits(int _n)
{
int count=0;
while (_n!=0)
{
_n/=10;
count++;
}
return count;
}
char digito(int _number, int _kdigit)
{
int flag=0, digit=0;
char ch='\0';
for (flag=0; flag<=_kdigit; flag++)
{
digit=_number%10;
_number/=10;
}
ch= digit + '0';
return ch;
}
Now the code is working pretty fine for relatively small numbers (up to 8 or 9 digits I would say).
But then something odd is happening: I tried to print the digits of the number 11111111111122 and obtained
The digit 0 of the number is 3;
The digit 1 of the number is 7;
The digit 2 of the number is 3;
The digit 3 of the number is 6;
The digit 4 of the number is 1;
The digit 5 of the number is 7;
The digit 6 of the number is 0;
The digit 7 of the number is 3;
I wonder why? Is it because it's a very large number? Because I tried even larger numbers and what happens is that the program enters the initial if clause that verifies the scanf reading. And that's ok. But the problem is that the program should also do the same with this number since it's bigger that the largest int.
Can someone help me fix this please?
Thanks!
There are two answers to two questions:
Q1) Why do I get wrong digits for the example?
A1) As others have commented: Because the example number is too high for the data type used, it matches the number which you find in the lower 32 bits: 30716370.
Q2) Why is the initial check "<0" not triggering for the example but does trigger for other, higher examples?
A2) Because the 30716370 is smaller than the biggest positive number which can be represented by a 32 bit signed int, which is 2147483647 == 0x7FFFFFFF. That one however is smaller (even in the number of digits, but that is not the point) than 11111111111122.
30716370 <
2147483647 <
11111111111122
The even higher numbers will by chance have the bit31 set, which makes the lower 32bit look negative. You could probably find other numbers which are too high but do not seem negative.
I've tried making a calculator that first reads the input from the user and then decides wheter the input is in binary or in decimal and then converts it.
i got almost everything but can't come up with the identifier! here's the code that i got:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int a;
char num[100];
int number[100];
int decimal_binary (int n);
int binary_decimal (int n);
void errorcode(void);
bool bin, decim;
int main (){
bin (false);
decim (false);
printf ("enter a number: ");
gets (num);
a = strlen(num);
if (a > 8){
errorcode();
//printf("That is an invalid number!");
//exit(45);
}
for (int i=0; i < a; i++){
number[i] = num[i] -'0';
printf("%d", number[i]);
}
int decimal_binary(int n){
int rem, i=1, binary = 0;
while (n != 0)
{
rem =n%2;
n/=2;
binary+=rem *i;
i*=10;
}
return binary;
}
int binary_decimal(int n)
{
int decimal = 0, i=0, rem;
while (n!-0){
rem = n%10;
n/=10;
decimal += rem *pow(2,i);
++i;
}
return decimal;
}
}
void errorcode(void){
printf("That is an invalid number!");
exit(45);
}
There is no such way to detect whether the number entered was binary or decimal just by analysing the characters of the number entered. However, if you study the Microsoft Windows calculator application that ships along with the OS, the "programmer" type of calculator takes an input whether the entered number is binary or decimal from the user, then internally in its code it would check whether the entered number was a valid binary or decimal number.
In short, your code will have to tell the user to specify what number is entered.
I would recommend studying the Microsoft calculator application's "programmer" type calc in order to help you understand what you want to achieve.
I believe the correct answer to this question is that binary numbers can be identified with the 0b prefix. Ex: 0b11111111 is the byte 0xFF, or 255 decimal. Notice the 0x prefix on the hex number. Decimal numbers have no prefix.. In fact, if you lead your 'decimal' number with a zero, the compiler will think that it is an octal number and treat it as base 8.
so this is the logic that came to my mind while trying to think of a procedure to convert
a binary number into a decimal number. I cannot seem to figure out what's wrong with the program which is preventing it from showing any kind of output at all.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,temp,r,rev,i, ct;
rev=0;
printf("Enter a number in base 10");
scanf("%d", &n);
// n is the decimal number
temp=n;
while(temp>0)
{
r=temp%2;
if (r==1)
break;
else
ct++;
temp/=2;
// ct will count the number of zeros from the top
}
while(temp>0)
{
r=temp%2;
rev=(rev*10 + r);
}
printf("%d", rev);
for(i=0;i<ct;i++)
{
printf("%i", 0);
}
return 0;
}
Your code has multiple problems:
1) ct is an uninitialized variable. Initialize it to 0.
2) The part that calculates the binary in single loop, needs temp=temp/2 to calculate the next digit in binary.
while(temp>0)
{
r=temp%2;
rev=(rev*10 + r);
temp/=2; // You need this
}
3) Your program can handle only a very small set of integers as you represent the binary number using an integer variable (rev). And you'll run into the integer overflows even when inputting small numbers such as 2047 (depending on whether the LSB of the binary is 1 and INT_MAX on your platform).
The code is giving false answers. İf number equals 42, it turns it to 101010. Ok, it is true. But if number equals 4, it turns it to 99. I didn't find the mistake. How can i fix the code?
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int i,digit,number=4;
long long bin= 0LL;
i=0;
while(number>0)
{
digit=number%2;
bin+=digit*(int)pow(10,i);
number/=2;
i++;
}
printf("%d ",bin);
getch();
}
Stop using floating point calculations for this. You are subject to the vagaries of floating point. When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point pow differently.
A simple change to make the code behave, and use integer arithmetic only, would be like this:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int digit,number=4;
long long scale,bin= 0LL;
scale=1;
while(number>0)
{
digit=number%2;
bin+=digit*scale;
number/=2;
scale*=10;
}
printf("%lld ",bin);
getch();
}
But I'd rather see the binary built up in a string rather than an integer.
You can use a simpler and easier approach to convert decimal to binary number system.
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
binary = (rem * place) + binary;
tempDecimal /= 2;
place *= 10;
}
printf("\nDecimal number = %lld\n", decimal);
printf("Binary number = %lld", binary);
return 0;
}