Posts Tagged ‘cpp’

Decimal to Roman Numeral Conversion

21. May 2009

No Comments »

#include <iostream>
#include <string>
using namespace std;

string dec_to_numeral(int x) {
    int dec[13] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    string num[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
    string numeral;

    for(int i = 0; i < 13; i++) {
        while (x >= dec[i]) {
            x -= dec[i];
            numeral.append(num[i]);
        }
    }

    return numeral;
}

int main() {
    //example
    cout << dec_to_numeral(400);

    return 0;
}

Monte Carlo Generation of Pi

21. May 2009

No Comments »

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main ()
{
    int in = 0;
    srand(time(NULL));

    for(int i = 0; i < 1000000; i++) {
        float x = (rand()%1000000)/1000000.0;
        float y = (rand()%1000000)/1000000.0;
        double r = sqrt((pow(x,2)+pow(y,2)));
        if(r <= 1) in++;
    }
    printf("percent error=%fn", ((((4*in/1000000.0)-3.141592)/3.141592)*100));
    printf("pi=%fn", (4*in/1000000.0));
    return 0;
}