我尝试在不使用&的情况下使用二进制数和逻辑运算符。当我输入示例1111和1000时,发生了浮点异常(核心转储)。我正在等待这个代码的长度相同的两个二进制数和打印后,例如打印: 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;
}发布于 2020-03-15 23:11:19
以下代码是问题的根源:
while(length_a/length_b!=1){/* 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;
} 您正在使用一种非常奇怪的方法来测试两个变量(length_a和length_b)是否相同!此外,如果length_b为零(在某些阶段看起来是零),则除法将导致错误。
您可以只使用这两个变量的简单比较:
if (length_a != 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;
}编辑:您的代码中还有许多其他错误,但我给出的建议将解决您所询问的特定错误。
发布于 2020-03-15 23:13:12
在您的程序中,浮点异常是由于函数长度被零除而发生的。在执行length()中的任何操作之前,应该检查a或b是否为0。尝试在长度的开头添加此内容
if(a == 0 || b == 0)
return 0;此外,在andop中将结果乘以10之前,请检查length()是否返回0,即将length(a, b)更改为
if(length(a, b) == 0)
break;即使在此之后,您的程序仍将以相反的顺序打印结果,因此您将不得不以相反的顺序打印结果。试着为此创建一个函数。
https://stackoverflow.com/questions/60694133
复制相似问题