首頁  >  文章  >  後端開發  >  使用C語言的除法和取模運算子將數字按照相反的順序列印出來

使用C語言的除法和取模運算子將數字按照相反的順序列印出來

PHPz
PHPz轉載
2023-08-27 12:53:051231瀏覽

使用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刪除