首页 > 解决方案 > 每次用户输入除数字以外的任何内容时都会打印“无效数字”的计算器

问题描述

因此,当我第一次输入除数字以外的任何内容时,程序会打印“无效数字 1”并重新循环。问题是:当它重新循环并且我输入程序期望的所有内容然后输入任何要重复的键时,我遇到了这个问题:我插入了除数字以外的任何内容,但这次它不打印“无效数字一”它跳过它并打印“插入运算符:错误”。基本上我希望这个计算器只要求我输入数字和 +/*/-// 但是当我不这样做时,它应该显示“Invalid num 1”或“Invalid operator”或“Invalid num 2”和然后让我重复,直到我输入正确的表格,然后它去执行下一行,依此类推!

注意:我刚开始学习 C,我想把到目前为止我学到的所有东西都放到这个计算器中。if/else/switch/printf/scanf/do...while/while/for/int/float/char/break/continue/ 这些是我迄今为止学到的东西!

#include<stdio.h>
int
main ()
{
  int num1, num2;
  int rst;
  char choice;
  int a = 43, b = 42, c = 45, d = 47;
  char i = a, f = b, g = c, h = d;
  char choix, n;
  do
    {
      printf ("\n\nPlease choice + or * or - or / for operater\n");
      printf ("\nPlease insert first number: ");
      scanf ("  %d", &num1);
      if (num1 != 0)
        {
          printf ("\nPlease insert an operater: ");
          scanf (" %c", &choice);
        }
      else
        {
          printf ("Invalid number 1");
        }
      if (choice == a)
        {
          printf ("\nPlease insert second number: ");
          scanf (" %d", &num2);
          rst = num1 + num2;
          printf ("%d + %d = %d", num1, num2, rst);
        }
      else if (choice == c)
        {
          printf ("\nPlease insert second number: ");
          scanf ("%d", &num2);
          rst = num1 - num2;
          printf ("%d - %d = %d", num1, num2, rst);
        }
      else if (choice == b)
        {
          printf ("\nPlease insert second number: ");
          scanf ("%d", &num2);
          rst = num1 * num2;
          printf ("%d * %d = %d", num1, num2, rst);
        }
      else if (choice == d)
        {
          printf ("\nPlease insert second number: ");
          scanf ("%d", &num2);
          rst = num1 / num2;
          printf ("%d / %d = %d", num1, num2, rst);
        }
      else if ((isdigit (choice) || isalpha (choice)))
        {
          printf ("Invalid operator");
        }

      printf ("\nDo you want to enter another pair of numbers(Y/N): ");
      scanf ("  %c", &choix);
      if (choix == 'n')
        {
          choix = 'N';
        }
    }
  while (choix != 'N');
  return 0;
}


标签: cif-statementscanfcalculatordo-while

解决方案


推荐阅读