简体   繁体   English

if..else if..else循环执行不正确

[英]if..else if..else loop not executing properly

I'm writing a program that asks the user to input a three digit number then adds each number by 6 with a modulus of 10. 我正在编写一个程序,要求用户输入一个三位数的数字,然后将每个数字加6,模数为10。

For example if I enter 619, the output I shall receive is 275. 例如,如果我输入619,则我将收到的输出是275。

My only problem is when I enter 100, I receive 1360, instead of 766 like I'm supposed to. 我唯一的问题是,当我输入100时,我会收到1360,而不是原来的766。

Here is what I have so far: 这是我到目前为止的内容:

int main()
{
    //declaring variables
    int numbers, newNumbers, input;
    int newInput = 0;

    //User input
    printf("Enter a three-digit number: ");

    //reads input (%d) and stores it as "input" (&input)
    scanf("%d", &input);

    //check if input is 3 digits. If not, print message
    if(input < 100 || input > 999)
    {
        printf("Invalid input, the number must be between 100 and 999 \n");
        return 0;
    }

    //loops program until input is 0
    while(input > 0)
    {
        //modulus 10
        numbers = input % 10;
        //adds 6 to input. Modulus 10
        newNumbers = (numbers + 6) % 10;

        //if input > 10, calculates new input
        if(input > 100)
            newInput = newNumbers;
        else if(input > 10)
            newInput = (newNumbers * 10) + newInput;
        else
            newInput = (newNumbers * 100) + newInput;

        input /= 10;
    }
//prints result
printf("Output: %d \n", newInput);
return 0;

}

In your code, by saying 在您的代码中,通过说

if(input > 100)
        newInput = newNumbers;
    else if(input > 10)
        newInput = (newNumbers * 10) + newInput;

you're not taking into account the numbers 100 and 10 themselves in the TRUE condition, whereas you should be counting them, too. 您并没有考虑处于TRUE条件的数字10010本身,而您也应该将它们计算在内。 You need to change the if condition to use >= , like 您需要更改if条件以使用>= ,例如

if(input >= 100)
        newInput = newNumbers;
    else if(input >= 10)
        newInput = (newNumbers * 10) + newInput;

Hi an easier solution is just this one: 您好,一个简单的解决方案就是:

output = (input + 666) % 1000; //Add 6 to all numbers
if(input % 10 > 3)             //Correct units carry
    output-=10;
if(input % 100 > 30)           //Correct tents carry 
    output-= 100;

It works and is easy scalable :) 它有效并且易于扩展:)

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

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