mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-23 22:09:46 +03:00
feat: improve conversions/binary_to_decimal.c
(#1262)
* Update binary_to_decimal.c 1. Removed the unused variable remainder. 2. Changed the variable name number to binary_number for clarity. 3. Removed the initialisation of number and temp since they are assigned values later. 4. Removed the newline character from the printf statement to improve readability. 5.Added a return statement at the end of main function. * Update binary_to_decimal.c
This commit is contained in:
parent
a555d2dd07
commit
6915d59738
@ -1,24 +1,37 @@
|
||||
/**
|
||||
* Modified 07/12/2017, Kyler Smith
|
||||
*
|
||||
*/
|
||||
* Modified 24/05/2023, Indrranil Pawar
|
||||
*
|
||||
* C program that converts a binary number to its decimal equivalent.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
int remainder, number = 0, decimal_number = 0, temp = 1;
|
||||
printf("\n Enter any binary number= ");
|
||||
scanf("%d", &number);
|
||||
int binary_number, decimal_number = 0, temp = 1;
|
||||
|
||||
// Iterate over the number until the end.
|
||||
while (number > 0)
|
||||
// Input the binary number
|
||||
printf("Enter any binary number: ");
|
||||
scanf("%d", &binary_number);
|
||||
|
||||
// Convert binary to decimal
|
||||
while (binary_number > 0)
|
||||
{
|
||||
remainder = number % 10;
|
||||
number = number / 10;
|
||||
decimal_number += remainder * temp;
|
||||
temp = temp * 2; // used as power of 2
|
||||
// Extract the rightmost digit of the binary number
|
||||
int digit = binary_number % 10;
|
||||
|
||||
// Multiply the rightmost digit with the corresponding power of 2 and add to the decimal number
|
||||
decimal_number += digit * temp;
|
||||
|
||||
// Remove the rightmost digit from the binary number
|
||||
binary_number /= 10;
|
||||
|
||||
// Increase the power of 2 for the next digit
|
||||
temp *= 2;
|
||||
}
|
||||
|
||||
printf("%d\n", decimal_number);
|
||||
// Output the decimal equivalent
|
||||
printf("Decimal equivalent: %d\n", decimal_number);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user