Problem
How to print the given two-digit number in reverse order with the help of division and Modulo operator using C programming language?
Solution
So far, we had seen how to reverse the string using string function and without string function. Now let’s see how to reverse the two-digit number without using the predefined function.
The logic we use to reverse the number with the help of operators is −
int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient
登录后复制
然后打印第一个数字,后面跟着第二个数字,然后你就会得到给定数字的逆序数字。
程序 1
在这个例子中,我们将取一个两位数,并应用除法和取模运算符来逆转数字−
#include
int main(){
int number;
printf("enter a number:");
scanf("%4d",&number);
int firstno=number%10; //stores remainder
int secondno=number/10;// stores quotient
printf("After reversing =%d%d
",firstno,secondno);
return 0;
}
登录后复制
Output
enter a number:45
After reversing =54
登录后复制
程序2
在这个例子中,我们将取一个3位数,并应用除法和取模运算符来反转这个数 −
在线演示
#include
int main(){
int number,num1,num2,num3,result;
printf("enter a number:");
scanf("%4d",&number);
num1 = number / 100;
num2 = (number % 100) / 10;
num3 = number%10 ;
result = 100*num3 + 10*num2 + num1;
printf("After reversing =%d
",result);
return 0;
}
登录后复制
Output
enter a number:479
After reversing =974
登录后复制
以上就是使用C语言的除法和取模运算符将数字按照相反的顺序打印出来的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!