c - 如何转换一个数字的数字?

标签 c

如果输入是整数[不是数组]:6977。我需要每 9 到 7 更改一次,因此结果将是:6777

这是我写的代码,这是我在想如何解决问题的想法,但这是错误的。我作业的重点是更改数字的特定数字[元素],但我不知道该怎么做。该函数应该做到这一点。更多示例:输入:12345555 [将每 5 更改为 3] 结果应为 12343333。

int function (int *n,int i){
    int temp=n[i]; //tepmorary veraible of the passed number
    int result=10;
    int devided;
    while (temp!=0){
        devided=temp%10;//get the last number example 123 = 3;
        if (devided==9){ //if its 9 change the last didigt to 7
            devided=7;
        }
        result*=devided;//multiply the last didgit with 10
        temp/=10;
    }

    return result;
}

void main (void){
    int a[100],i=0;
    while (scanf_s ("%d",&a[i])){
        printf ("%d",function(a,i));
        i++;
    }
}

最佳答案

你的result*=devided;逻辑是错误的。您需要将数字(乘以 10 位)添加到结果中。这是您问题的解决方案。

int function (int *n, int i){
    int temp=n[i]; //tepmorary veraible of the passed number
    int result=0;
    int mult=1;
    int devided;
    while (temp!=0){
        devided=temp%10;//get the last number example 123 = 3;
        if (devided==9){ //if its 9 change the last didigt to 7
            devided=7;
        }
        result+=(devided * mult);//multiply the last didgit with 10
        temp/=10;
        mult*=10;
    }
    return result;
}

关于c - 如何转换一个数字的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57874155/

相关文章:

c - C 控制台应用程序 : Differences between different types of inputting string in a console application C 中的最佳输入方式

c++ - 如何在 C/C++ 中提交 SQLite 事务?

arrays - 查找数组的长度和指针指向数组的长度

c - float 和双输出

c - Execvp 输出太大时挂起?

c++ - C 平衡二叉树 vs C++ std::map 性能

c - 指向数组的指针和指向指针的指针的内存分配

c - 如何安全地从 C 中的数据包中读取数据?

c - 函数退出(退出代码)是否关闭了套接字描述符?

c - VPATH 构建中未考虑 EXTRA_DIST