C++程式獲取給定數字的幅度
給定數字的幅度是指該特定數字與零之間的差。它也可以指數學物件相對於同類其他物件的尺寸。這裡我們將遵循第一個定義,數字的幅度或絕對值表示為|x|,其中x是實數。我們將探討顯示給定實數的絕對值或幅度的方法。
樸素方法
我們可以自己編寫一個程式來找出給定實數的幅度。下面解釋了示例。
語法
int value;
if (value < 0) {
value = (-1) * value;
}
演算法
- 將輸入儲存到數值變數(整數/雙精度浮點數)中。
- 如果數字 < 0,則
- 數字 := 數字 * (-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++ 程式語言中有效的兩種方法。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP