【发布时间】:2020-03-15 14:49:42
【问题描述】:
我正在尝试使用二进制数和逻辑运算符而不使用&。当我输入示例 1111 和 1000 时,发生了浮点异常(core dumped)。我正在等待此代码相同长度的两个二进制数,打印后例如 print:1001 和 1111 = 1001
#include<stdio.h>
int length(int a,int b);
int andop(int a,int b);
int main(){
int first,sec;
do{
printf("First integer: ");
scanf("%d",&first);
printf("\nSecond integer: ");
scanf("%d",&sec);}
while(andop(first,sec)==0);
printf("\n%d AND %d= %d",first,sec,andop(first,sec));
return 0;
}
int andop(int a,int b){
int a_1,b_1;
int result=0;
a_1=a;
b_1=b;
while(a_1>1){/*Checking if first is binary or not,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (a_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
a_1=a_1/10;
}
while(b_1>1){/*Checking if first is binary ,the loop briefly checks if the number in each digits either 1 or 0,and if it dont returns 0 it also quit the loop and stop asking for new numbers*/
if (b_1%10>1){
printf("\nInteger should be binary,please enter 2 new integers\n");
return 0;
}
b_1=b_1/10;
}
while (length(a,b)>0){
result=result+(a%10)*(b%10);
a=a/10;
b=b/10;
if(length(a,b) == 0){
break;
}
result=result*10;
}
return result;
}
int length(int a,int b){
if(a == 0 || b == 0){
return 0;
}
int temp_a,temp_b;
int length_a=0,length_b=0;
temp_a=a;/*i assign the number into the temporary variable _a and _b*/
temp_b=b;
while(temp_a>0){//checking how many digit a is
temp_a=temp_a/10;
length_a++;
}
while(temp_b>0){//checking how many digit b is
temp_b=temp_b/10;
length_b++;
}
if(length_!=length_b){/* If they don't have same digits ,print an error message and continue to taking number from user*/
printf("\nInteger should have same length,please enter 2 new integers\n");
return 0;
}
return length_a;
}
【问题讨论】:
-
错误是“除以零”,对吧?所以检查你的部门。
-
我到底在哪里做这个?
-
查看您的所有
/运算符。如果除数是常数(0 除外),则不是问题。这应该会迅速减少可能性。并使用调试器。 -
while(length_a/length_b!=1) {...}循环不好。使用if(length_a != length_b) { ..} -
是的,我做了一些编辑,但我仍然犯了同样的错误。它可能应该在 int andop(int ,int) 但我找不到问题所在?