【问题标题】:no results when zero is an operand in calculator program当零是计算器程序中的操作数时没有结果
【发布时间】:2014-01-10 09:33:02
【问题描述】:

我正在使用 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 但是不打印计算结果直接退出程序?

谁能说出问题出在哪里?

【问题讨论】:

  • @A4L - OP 在这里谈论 2 个数字,而不是一个浮点数。
  • 您需要处理 所有 NaN 案例,例如1/0 1%0 等
  • 我输入了 2,0,因为两个输入必须用 , 分隔,
  • @OliCharlesworth 2 % 0 在哪里?
  • @Salahuddin 在这里:first%second

标签: c printf scanf


【解决方案1】:

2%0 是未定义的行为。

这将在除以零后给您提醒。除以零是undefined

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试试这个

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

      也尽量避免使用scanf(),而是使用 fgets() 然后使用sscanf()strtok(), atoi() 检索内容。 scanf() 使用起来可能有点复杂,而且很容易出错。

      【讨论】:

        【解决方案4】:

        Floating point exception 由于被零除。

        您说您尝试使用调试器,但没有提及调试器错误。

        gdb 给出以下错误

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-16
          • 1970-01-01
          • 2023-02-14
          • 2022-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多