首頁  >  文章  >  後端開發  >  取得給定數字的大小的C++程序

取得給定數字的大小的C++程序

WBOY
WBOY轉載
2023-08-29 12:29:12987瀏覽

取得給定數字的大小的C++程序

給定數字的大小意味著該特定數字之間的差異 和零。它也可以表示一個數學物件相對於該數學物件中其他物件的大小 同種。我們將遵循這裡的第一個定義,以及大小或絕對值 數字的表示為 |x|,其中 x 是實數。我們探索展示的方式 給定實數的絕對值或大小。

樸素方法

我們可以自己寫一個程式來找出給定實數的大小。這 下面解釋了範例。

文法

int value;
if (value < 0) {
   value = (-1) * value;
}

演算法

  • 在數值變數(整數/雙精度)中取得輸入。
  • 如果數字
    • 數字 := 數字 * (-1)
  • 否則,
    • 按原樣返回號碼。

範例

#include <iostream>
using namespace std;

// finds the magnitude value of a given number
int solve(int value){
   
   // if smaller than zero, then multiply by -1; otherwise return the number itself
   if (value < 0) {
      value = (-1) * value;
   }
   
   // return the magnitude value
   return value;
}
int main(){
   int n = -19;

   //display the number and its magnitude
   cout << "The number is: " << n << endl;
   cout << "The magnitude value of the number is: " << solve(n) << endl;
   return 0;
}

輸出

The number is: -19
The magnitude value of the number is: 19

使用abs()函數

abs() 函數傳回給定數字的絕對值或大小值。它 支援所有數值類型,並且可在 C STL 中使用。

文法

double value;
double absValue = abs(value);

演算法

  • 在名為 value 的變數中取得數字輸入。 (名稱可以是任何內容)

  • 使用abs()函數轉換為給定變數的絕對/幅度值。

  • 顯示/使用震級值。

範例

#include <iostream>
using namespace std;

// finds the magnitude value of a given number
double solve(double value){

   // return the magnitude value using the abs function
   return abs(value);
}
int main(){
   double n = -197.325;
   
   //display the number and its magnitude
   cout << "The number is: " << n << endl;
   cout << "The magnitude value of the number is: " << solve(n) << endl;
   return 0;
}

輸出

The number is: -197.325
The magnitude value of the number is: 197.325

結論

各種數學運算都需要決定震級值。因為 其中,我們必須設計方法來找出震級值並學習 輸出相同的各種內建函數。在給定的文章中,我們討論了 這兩種方法都適用於 C 程式語言。

以上是取得給定數字的大小的C++程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除