Как выйти из программы, введя символ q один раз, а не два? - PullRequest
0 голосов
/ 28 января 2019

Как выйти из программы, введя символ q один раз, а не дважды?

Почему мне нужно еще раз ввести "q"?

Мне кажется, что выражение || scanf("%c", &operation) не работал.

/*
 * Name: Calculator.
 * Description: Calculator for simple math operations.
 *
 * Compiler: Apple LLVM version 10.0.0 (clang-1000.11.45.5).
 * Coding style: Google.
 */

#include <locale.h>
#include <math.h>
#include <stdio.h>

#define TRUE 1
#define EXIT 'q'

double add(double x, double y);
double subtract(double x, double y);
double multiply(double x, double y);
double divide(double x, double y);
double degree(double x, int y);
double sqrt(double x);          
double mod(double x, double y);
double div(double x, double y);

int main(void) {
  char *locale = setlocale(LC_ALL, "");

  printf("Examples:\n\n");

  printf("1 + 2\n");
  printf("1 - 2\n");
  printf("1 * 2\n");
  printf("1 / 2\n");
  printf("1 ^ 2\n");
  printf("(sqrt): s 2\n");
  printf("(mod): 1 m 2\n");
  printf("(div): 1 d 2\n\n");

  printf("Input for exit: \"q\"\n\n");

  while (TRUE) {
    double x, y;
    char operation;

    scanf("%lf %c %lf", &x, &operation, &y) ||
        scanf("%c %lf", &operation, &x) || scanf("%c", &operation);

    switch (operation) {
      case ' ':
        break;

      case '\n':
        break;

      case '+':
        printf("Result = %.2lf\n", add(x, y));
        break;

      case '-':
        printf("Result = %.2lf\n", subtract(x, y));
        break;

      case '*':
        printf("Result = %.2lf\n", multiply(x, y));
        break;

      case '/':
        if (y != 0) {
          printf("Result = %.2lf\n", divide(x, y));
        } else {
          printf("\nError!.\n");
        }
        break;

      case '^':
        printf("Result = %.2lf\n", degree(x, y));
        break;

      case 's':
        printf("Result = %.2lf\n", sqrt(x));
        break;

      case 'm':
        printf("Result = %.2lf\n", divide(x, y));
        break;

      case 'd':
        printf("Result = %.2lf\n", divide(x, y));
        break;

      case EXIT:
        printf("Input symbol \"%c\"\nExit...\n", EXIT);
        return 0;
    }
  }

  return 0;
}

double add(double x, double y) { return (x + y); }

double subtract(double x, double y) { return (x - y); }

double multiply(double x, double y) { return (x * y); }

double divide(double x, double y) { return (x / y); }

double degree(double x, int y) {
  int response = 1;
  while (y) {
    if (y & 1) response *= x;
    x *= x;
    y >>= 1;
  }
  return response;
}

Ответы [ 2 ]

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

Ваши scanf вызовы [вероятно] будут мешать друг другу.

Если первый вызов не удастся, он [вероятно] нарушит другие (т. Е. Первый уже извлек данные из * 1004).*, так что остальные ничего не увидят).

Более верный способ - использовать fgets и sscanf в результирующем буфере:

 do {
    char buf[1000];

    fgets(buf,sizeof(buf),stdin);

    if (sscanf(buf,"%lf %c %lf", &x, &operation, &y) == 3)
        break;

    if (sscanf(buf,"%c %lf", &operation, &x) == 2)
        break;

    if (sscanf(buf,"%c", &operation) == 1)
        break;

    // error ...
} while (0);
0 голосов
/ 28 января 2019

Я думаю, что приведенный ниже фрагмент кода ответит на ваш вопрос.

#include<stdio.h>


void main(){

double x,y;
char operation='n';
int i;

printf("Enter the variables\n");

i=scanf("%lf %c %lf",&y, &operation, &x);
printf("This is operation, %c and this is long float %lf, this is y %lf  and i %d\n",operation,x,y, i);

i=scanf("%c %lf", &operation, &x);
printf("This is operation, %c and this is long float %lf, this is y %lf  and i %d\n",operation,x,y, i);

i=scanf("%c", &operation);
printf("This is operation, %c and this is long float %lf, this is y %lf  and i %d\n",operation,x,y, i);

}

Это вывод, который я получил

Enter the variables
x
This is operation, n and this is long float 0.000000, this is y 0.000000  and i 0
x
This is operation, x and this is long float 0.000000, this is y 0.000000  and i 1
This is operation, x and this is long float 0.000000, this is y 0.000000  and i 1

То, что происходит, - то, что первый оператор scanf читает вашвведите 'q' и отбрасывает буфер, так как он не отформатирован должным образом, и возвращает 0. Это вызывает запуск второго scanf.

Второй scanf считывает ваш 'q', добавляет его в объект операции и возвращает'1', в результате чего третий сканд не запускается.

Я бы предложил лучший способ решить эту проблему - сохранить стандартную форму ввода.Всегда сначала берите символы, а потом удваивайте.

Также следите за тем, что возвращает scanf.Возвращает количество идентификаторов, правильно проанализированных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...