【问题标题】:Character reading after the integer整数后的字符读取
【发布时间】:2022-06-16 23:25:21
【问题描述】:

我尝试了一个简单的计算器练习。尽管我的逻辑是正确的。我一直在努力寻找为什么我无法读取两个整数之后的字符。

下面给出的代码不起作用(首先获取数字,然后将操作作为字符)。但是在相同的代码中,如果我先读取字符,然后再读取数字,它就可以正常工作。没有得到这背后的逻辑:(

#include <stdio.h>
#include <stdint.h>

void add (unsigned int temp1, unsigned int temp0);
void subtract (unsigned int temp1, unsigned int temp0);
void multiply (unsigned int *temp);
void divide (unsigned int *temp);

int main()
{
    unsigned int num[2];
    char op;

    printf("Enter two numbers\n");
    scanf("%u", &num[0]);
    scanf("%u", &num[1]);
   
    printf("Enter operation\n");
    scanf("%c", &op);

    switch(op)
    {
        case '+': add(num[0],num[1]);
        break;

        case '-': subtract(num[0],num[1]);
        break;

        case '*': multiply(num);
        break;

        case '/': divide(num);
        break;

        default: printf("Invalid Operation");
        break;
    }

    return 0;
}


void add (unsigned int temp1, unsigned int temp0)
{
    printf("Sum of the numbers is: %u", temp1+temp0);
}

void multiply (unsigned int *temp)
{
    printf("Product of the numbers is: %u", temp[0]*temp[1]);
}

void subtract (unsigned int temp1, unsigned int temp0)
{
    if (temp1 > temp0)
    {
        printf("Difference of the numbers is: %u", temp1-temp0);
    }
    else
    {
        printf("Difference of the numbers is: %u", temp0-temp1);
    }
}

void divide (unsigned int *temp)
{
    unsigned int quo;
    unsigned int rem;
    
    quo = temp[0]/temp[1];
    rem = temp[0]%temp[1];
    
    printf("Quotient of %u divided by %u is: %u\n", temp[0], temp[1], quo);
    printf("Remainder of %u divided by %u is: %u\n", temp[0], temp[1], rem);
}

【问题讨论】:

  • 与其他说明符不同,%c 不使用前导空格。使用scanf(" %c", &amp;op);"% 之间添加一个空格。

标签: c


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多