将4位整数除以2位整数并用c计算

时间:2019-03-14 08:24:48

标签: c

///从键盘输入一个4位整数n,然后编写一个程序将其分为两个2位整数a和B。计算并输出加,减,乘,除和冗余运算的结果的两个数之和。例如,n = -4321,如果拆分后的两个整数是a和b,则a = -43和b = -21。除法运算的结果要求精确到小数点后两位,数据类型为float。冗余和除法运算需要考虑除法0,即,如果分割B = 0,则输出提示信息“第二个运算符为零!”

//未能通过测试,我该如何解决

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

int main()
{
    int x, a, b;
    printf("Please input n:\n");
    scanf("%d", &x);
    a = x / 100;
    b = x % 100;
    printf("%d,%d\n", a, b);
    printf("sum=%d,sub=%d,multi=%d\n", a + b, a - b, a*b);
    if (b == 0)
        printf("The second operater is zero!");
    else
        printf("dev=%.2f,mod=%d\n", (float)a / b, a%b);
}

1 个答案:

答案 0 :(得分:1)

您忘记检查x是4位数字。因此,如果输入是12345123,则不满足要求。

#include <stdio.h>

int main()
{

    int x, a, b;
    int passed = 0;

    // Enter a 4 digits number: ABCD
    do {
        printf("Enter X = ");
        scanf("%d", &x);
        passed = (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000);
    } while (!passed);

    a = x / 100;
    b = x % 100;

    printf("Numbers: %d %d \n", a, b);

    printf("Sum = %d \n", a + b);
    printf("Sub = %d \n", a - b);
    printf("Mul = %d \n", a * b);
    if (0 == b) {
        printf("Div by Zero \n");    
    } else {
        printf("Div = %f \n", (double)a / b);
        printf("Mod = %d \n", a % b);
    }

    return 0;
}