与えられた数の2の補数を見つけるCプログラム
特定の2進数の2の補数は、次の2つの方法で計算できます-
-
方法1 −指定された2進数を1の補数に変換してから、1を加算します。
-
方法2 −最下位ビット(LSB)から設定された最初のビットの後の後続ゼロは、変更されずに残っているものも含めて、補完する必要があります。
2の補数を見つけるためのロジック 与えられた2進数の場合は次のとおりです-
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
} else {
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two); 1の補数を見つけるためのロジック 与えられた2進数からは-
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one); 例
以下は、与えられた数の2の補数を見つけるCプログラムです-
#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
int i, carry = 1;
char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
printf("Enter the binary number\n");
gets(num);
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
}
else{
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two);
return 0;
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Enter the binary number 1000010 Ones' complement of binary number 1000010 is 0111101 Two's complement of binary number 1000010 is 0111110
-
与えられた数がフィボナッチ数であるかどうかをチェックするためのJavaプログラム?
以下は、指定された番号がフィボナッチであるかどうかを確認するJavaプログラムです- 例 public class Demo{ static boolean perfect_square_check(int val){ int s = (int) Math.sqrt(val); return (s*s == val); } static boolean fibonacci_num_check(int n){
-
与えられた2つの日付の間の日数を見つけるPythonプログラム
2つの日付の間の日数を見つけるために、Pythondatetimeモジュールを使用しています。まず、必要なライブラリをインポートします- from datetime import date 日付オブジェクトを作成し、日数を計算する日付を入力します- date1 = date(2021, 7, 20) date2 = date(2021, 8, 30) 上記の2つの日付の差を日数の形式で取得します- (date2 - date1).days 例 以下はコードです- from datetime import date # both the dates date1 = date(2021