首页 > 解决方案 > 打印给定 4 位数字的副本,但每个素数后面都跟着比它大 1 的数字

问题描述

所以我一直在尝试创建一个程序,它要求用户输入一个 4 位数字,并打印它的副本,但每个素数后面都跟着一个比它大的数字。(例如 2345 变为 2334456)

所以我尝试的是首先找到存储所有数字,然后将它们作为字符串打印出来,如果它们中的任何一个是素数,则使用 if 语句将它们打印出来。现在这似乎给出了与我预期不同的输出。例如,2345 给出 23235656。我哪里做错了?

#include <stdio.h>

int main() {
    unsigned int userinput;
    unsigned int onesplace;
    unsigned int tensplace;
    unsigned int hundredsplace;
    unsigned int thousandsplace;
    printf("Please print your number /n");
    scanf("%u", &userinput);
    onesplace = userinput%10;
    tensplace = ((userinput-onesplace/10))%10;
    hundredsplace = ((userinput - onesplace -10*tensplace)/100)%10;
    thousandsplace = ((userinput - onesplace - 10*tensplace - 100*hundredsplace)/1000);
    printf("%u", thousandsplace);

    if ((thousandsplace == 2)||(thousandsplace == 3)||(thousandsplace == 5)||(thousandsplace == 7)) {
        unsigned int newnum = thousandsplace + 1;
        printf("%u", newnum);
    }
    printf("%u", hundredsplace);
    if ((hundredsplace == 2)||(hundredsplace == 3)||(hundredsplace == 5)||(hundredsplace == 7)) {
        unsigned int newnum2 = hundredsplace + 1;
        printf("%u", newnum2);
    }
    printf("%u", tensplace);
    if ((tensplace == 2)||(tensplace == 3)||(tensplace == 5)||(tensplace == 7)) {
        unsigned int newnum3 = tensplace + 1;
        printf("%u", newnum3);
    }
    printf("%u", onesplace);
    if ((onesplace == 2)||(onesplace == 3)||(onesplace == 5)||(onesplace == 7)) {
        unsigned int newnum4 = onesplace + 1;
        printf("%u", newnum4);
    }
}

标签: c

解决方案


您错误地计算了 tensplace,基本上忘记了将 10 值除以 10。

更改(userinput-onesplace/10)(userinput/10)

然后输入 2345 你得到输出

Please print your number /n2334456

因为我使用了https://www.tutorialspoint.com/compile_c_online.php(非交互式提供的标准输入),所以可能不需要的“/n”在单个输出行中可见,这是一个单独的不相关问题。


推荐阅读