首页  >  文章  >  后端开发  >  使用C语言的除法和取模运算符将数字按照相反的顺序打印出来

使用C语言的除法和取模运算符将数字按照相反的顺序打印出来

PHPz
PHPz转载
2023-08-27 12:53:051247浏览

使用C语言的除法和取模运算符将数字按照相反的顺序打印出来

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<stdio.h>
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</p><p>",firstno,secondno);
   return 0;
}

Output

enter a number:45
After reversing =54

程序2

在这个例子中,我们将取一个3位数,并应用除法和取模运算符来反转这个数 −

 在线演示

#include<stdio.h>
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</p><p>",result);
   return 0;
}

Output

enter a number:479
After reversing =974

以上是使用C语言的除法和取模运算符将数字按照相反的顺序打印出来的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除