知識社群登入
位置: AutoCAD開放式教學 > 討論區 > 討論
樣板函式
1樓
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;
// --------------------------------------------------------

template <class T>
T abs1(T a); //宣告abs1的樣板函式,並宣告T為型別代名
// --------------------------------------------------------

int main(int argc, char *argv[])
{
    int i;
    double d;
    cout << "  請輸入一個整數 i:" ;
    cin >> i;
    cout << "請輸入一個浮點數 d:";
    cin >> d;
    cout << "i 的絕對值:" << abs1(i)<< endl;
    cout << "d 的絕對值:" << abs1(d) << endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}
// --------------------------------------------------------

// 定義 abs1 樣板函式 的主體,傳入及傳回的資料型別為代名T

template <class T>
T abs1(T a)
{
    if (a < 0)
    {
a= -(a);
    }
    return a;
}

2樓

Example

/* FMOD.C: This program displays a
 * floating-point remainder.
 */

#include <math.h>
#include <stdio.h>

void main( void )
{
   double w = -10.0, x = 3.0, y = 0.0, z;

   z = fmod( x, y );
   printf( "The remainder of %.2f / %.2f is %f\n", w, x, z );
   printf( "The remainder of %.2f / %.2f is %f\n", x, y, z );

}

Output

The remainder of -10.00 / 3.00 is -1.000000
// -----------------------------------------

fabs()

Example

/* ABS.C: This program computes and displays
 * the absolute values of several numbers.
 */

#include  <stdio.h>
#include  <math.h>
#include  <stdlib.h>

void main( void )
{
   int    ix = -4, iy;
   long   lx = -41567L, ly;
   double dx = -3.141593, dy;

   iy = abs( ix );
   printf( "The absolute value of %d is %d\n", ix, iy);

   ly = labs( lx );
   printf( "The absolute value of %ld is %ld\n", lx, ly);

   dy = fabs( dx );
   printf( "The absolute value of %f is %f\n", dx, dy );
}

Output

The absolute value of -4 is 4
The absolute value of -41567 is 41567
The absolute value of -3.141593 is 3.141593