简体   繁体   English

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

[英]divide a 4-digit integer into 2-digit integers and calculate by c

//Enter a 4-digit integer n from the keyboard, and write a program to divide it into two 2-digit integers a and B. Calculate and output the results of the addition, subtraction, multiplication, division and redundancy operations of the split two numbers. //从键盘输入一个4位整数n,并编写一个程序将其分为两个2位整数a和B。计算并输出分割结果的加,减,乘,除和冗余运算结果两个数字。 For example, n=-4321, if the two integers after splitting are a and b, then a=-43 and b=-21. 例如,n = -4321,如果拆分后的两个整数是a和b,则a = -43和b = -21。 The result of division operation requires that it be precise to 2 decimal places, and the data type is float. 除法运算的结果要求精确到小数点后两位,数据类型为float。 Redundancy and division operations need to take into account the division of 0, that is, if the split B = 0, then output the prompt information "The second operator is zero!" 冗余和除法运算需要考虑除法0,即,如果分割B = 0,则输出提示信息“第二个运算符为零!”。

//Failure to pass the test,how should i fix //未能通过测试,我该如何解决

#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);
}

You forgot to check that x is a 4-digits number. 您忘记检查x是4位数字了。 So if the input is 12345 or 123 you don't satisfy the requirement. 因此,如果输入的是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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM