零是计算器程序中的操作数时没有结果

时间:2014-01-10 09:33:03

标签: c printf scanf

我正在使用C

编写计算器程序
/*
 * sum.c
ch 2
1.Write a program in “SUM.C” which reads two integers and prints out the sum,
the difference and the product. Divide them too, printing your answer to two
decimal places. Also print the remainder after the two numbers are divided.
Introduce a test to ensure that when dividing the numbers, the second number
is not zero.
What happens when you add two numbers and the sum is too large to fit into
the data type you are using? Are there friendly error messages?

 *
 *  Created on: Jan 10, 2014
 *      Author: salahuddin
 */


#include<stdio.h>

int main(void)
{
    int first,second;

    printf("Please enter two number a,b");
    scanf("%i,%i",&first,&second);

    printf("sum=%i,   difference=%i,   product=%i,    ",
            first+second,first-second,first*second);

    if(second!=0)
        printf("division=%.2lf,    ",(double)first/(double)second);
    else
        printf("remainder=%i",first%second);

return 0;
}

输入0以外的数字时效果很好 当我输入2,0作为输入时,没有任何东西出现

我试图在eclipse中使用调试器调试它,这两个变量的值为2,0 但它没有打印计算结果并直接退出程序?

任何人都可以告诉问题在哪里吗?

4 个答案:

答案 0 :(得分:1)

2%0是未定义的行为。

这会在除以零后给你提醒。除以零是undefined

答案 1 :(得分:1)

您的程序可能因为除零而被终止。如果您有更多的换行和/或刷新调用,您可能会看到输出直到程序死亡。

答案 2 :(得分:1)

试试这个

if(second!=0)
{
  printf("division=%.2lf,    ",(double)first/second);
  printf("remainder=%i",first%second);
}

尽量避免使用scanf()而是使用读取用户输入 fgets()然后使用sscanf()strtok(), atoi()检索内容。 使用scanf()可能有点复杂,很容易出错。

答案 3 :(得分:0)

因为除以零而

Floating point exception

你说你试过调试器,但没有提到调试器错误。

gdb给出了以下错误

Program received signal SIGFPE, Arithmetic exception.
0x08048516 in main () at test.c:16
   16           printf("remainder=%i",first%second);