落書きノート

ふと自分が気になった事を書いてます

C++で問題を解く

C++が終わるまでRubyは後回しにすることに。とりあえず今日はここまで。

#include <iostream>

using namespace std;

short absolute(short x){
  return x >= 0 ? x : -x;
}

int absolute(int x){
  return x >= 0 ? x : -x;
}

long absolute(long x){
  return x >= 0 ? x : -x;
}

float absolute(float x){
  return x >= 0 ? x : -x;
}

double absolute(double x){
  return x >= 0 ? x : -x;
}

long double absolute(long double x){
  return x >= 0 ? x : -x;
}

int main(void){
  short s; int i; long l;
  float f; double d; long double x;

  cout << "short型:"; cin >> s;
  cout << "int型:"; cin >> i;
  cout << "long型:"; cin >> l;
  cout << "float型:"; cin >> f;
  cout << "double型:"; cin >> d;
  cout << "long double型:"; cin >> x;

  cout << "short型の絶対値:" << absolute(s) << endl;
  cout << "int型の絶対値:" << absolute(i) << endl;
  cout << "long型の絶対値:" << absolute(l) << endl;
  cout << "float型の絶対値:" << absolute(f) << endl;
  cout << "double型の絶対値:" << absolute(d) << endl;
  cout << "long double型の絶対値:" << absolute(x) << endl;

  return 0;
}


#include <iostream>

using namespace std;

inline double square(double x){
  return x * x;
}

inline double cube(double x){
  return x * x * x;
}

int main(void){
  double x;
  cout << "実数値:"; cin >> x;
  cout << square(x) << endl;
  cout << cube(x) << endl;
  return 0;
}



#include <iostream>

using namespace std;

int main(void){
  int n = 135;
  cout << n << endl;
  cout << &n << endl;
  int* ptr = &n;
  cout << ptr << endl;
  cout << *ptr << endl;
  cout << &ptr << endl;
  return 0;
}



#include <iostream>
#include <typeinfo>

using namespace std;

int main(void){
  int n;
  int* ptr;

  cout << typeid(n).name() << endl;
  cout << typeid(&n).name() << endl;
  cout << typeid(ptr).name() << endl;
  cout << typeid(*ptr).name() << endl;
  cout << typeid(&ptr).name() << endl;
  
  return 0;
}




#include <iostream>

using namespace std;

void swap(int* a, int* b){
  int t = *a;
  *a = *b;
  *b = t;
}

int main(void){
  int a,b;
  cout << "a:"; cin >> a;
  cout << "b:"; cin >> b;
  cout << "交換前 a:" << a << " b:" << b << endl;
  swap(&a,&b);
  cout << "交換後 a:" << a << " b:" << b << endl;
  return 0;
}




#include <iostream>

using namespace std;

void sort(int*,int*,int*);
void swap(int*,int*);

void sort(int* a, int* b, int* c){
  if(*a > *b)
    swap(a,b);
  if(*b > *c)
    swap(b,c);
  if(*a > *b)
    swap(a,b);
}

void swap(int* a, int* b){
  int t = *a;
  *a = *b;
  *b = t;
}

int main(void){
  int a,b,c;

  cout << "a:"; cin >> a;
  cout << "b:"; cin >> b;
  cout << "c:"; cin >> c;

  sort(&a,&b,&c);

  cout << "a:" << a << " b:" << b << " c:" << c << endl;

  return 0;
}