Не получается вывод для деления и модуля - PullRequest
0 голосов
/ 19 января 2019

Приведенная ниже программа на C дает мне вывод только для сложения (+), разности (-), умножения (*). Но когда я пытаюсь использовать деление (/) и модуль (%), программа просто закрывается без каких-либо ошибок. Помоги мне, я новичок в программировании на Си.

//A simple calculator.

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, sum, diff, rem, multi;
float div;
char character;
clrscr();
printf("Choose the character you want to use(+, -, *, /, %): ");
scanf("%c", &character);
switch(character)
{
case '+': //will be used for addition.
    printf("Enter the first and second number: ");
    scanf("%d %d", &a, &b);
    sum = a+b;
    printf("The sum of the %d and %d is %d", a, b, sum);
    break;
case '-': //will be used for difference.
    printf("Enter the first and second number: ");
    scanf("%d %d", &a, &b);
    diff = a-b;
    printf("The difference between %d and %d is %d", a, b, diff);
    break;
case '%': //will be used for modulus.
    printf("Enter the first and second number: ");
    scanf("%f %f", &a, &b);
    rem = a%b;
    printf("The remainder of %f and %f is %f", a, b, rem);
    break;
case '*': //will be used for product of 2 no.
    printf("Enter the first and second number: ");
    scanf("%d %d", &a, &b);
    multi = a*b;
    printf("The multiplication of %d and %d is %d", a, b, multi);
    break;
case '/': //will be used for the division.
    printf("Enter the first and second number: ");
    scanf("%f %f", &a, &b);
    div = a/b;
    printf("The division of %f and %f is %f", a, b, div);
    break;
default:
    printf("Error! character please retry");
}
getch();
}

Ответы [ 3 ]

0 голосов
/ 19 января 2019

При использовании / и % используйте

scanf("%d %d", &a, &b);

вместо

scanf("%f %f", &a, &b);

потому что% f используется для переменных типа float, тогда как в случае / и% % d используется

0 голосов
/ 19 января 2019

Вы используете неправильные форматы.После включения -Wall в gcc и исправления предупреждений я получаю работающую программу.Вы также пропускаете \n в своем ответе printf() *

#include <stdio.h>

int main(int argc, char **argv)
{
  int a, b, sum, diff, rem, multi;
  float div;
  char character;
  printf("Choose the character you want to use(+, -, *, /, %%): ");
  scanf("%c", &character);
  switch(character)
    {
    case '+': //will be used for addition.
      printf("Enter the first and second number: ");
      scanf("%d %d", &a, &b);
      sum = a+b;
      printf("The sum of the %d and %d is %d\n", a, b, sum);
      break;
    case '-': //will be used for difference.
      printf("Enter the first and second number: ");
      scanf("%d %d", &a, &b);
      diff = a-b;
      printf("The difference between %d and %d is %d\n", a, b, diff);
      break;
    case '%': //will be used for modulus.
      printf("Enter the first and second number: ");
      scanf("%d %d", &a, &b);
      rem = a%b;
      printf("The remainder of %d and %d is %d\n", a, b, rem);
      break;
    case '*': //will be used for product of 2 no.
      printf("Enter the first and second number: ");
      scanf("%d %d", &a, &b);
      multi = a*b;
      printf("The multiplication of %d and %d is %d\n", a, b, multi);
      break;
    case '/': //will be used for the division.
      printf("Enter the first and second number: ");
      scanf("%d %d", &a, &b);
      div = a/b;
      printf("The division of %d and %d is %f\n", a, b, div);
      break;
    default:
      printf("Error! character please retry");
    }
}

Результаты теста:

$ ./dummy
Choose the character you want to use(+, -, *, /, %): %
Enter the first and second number: 5 2
The remainder of 5 and 2 is 1
$
0 голосов
/ 19 января 2019

Вы используете спецификатор формата %f для int переменных в случаях / и %.

scanf("%f %f", &a, &b);

Таким образом, вызывая неопределенное поведение.

Измените его следующим образом.

scanf("%d %d", &a, &b);

%f используется для чтения переменных с плавающей точкой.


Если вы хотите получить результат с плавающей точкой для деления, вам нужно привести один из аргументов к плавающей, вместо этого читая их как float.

  div = (float)a/b;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...