落書きノート

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

C言語で問題を解く

#include <stdio.h>

int card_convr(unsigned x, int n, char d[]) {
  char dchar[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  int digits = 0;
  int i;
  
  if(x == 0)
    d[digits++] = dchar[0];
  else
    while(x) {
      printf("%d |     %4d   ···  %d\n", n, x, x % n);
      printf("  +------------\n");
      d[digits++] = dchar[x % n];
      x /= n;
    }
  printf("        %4d\n", x);
  for(i = 0; i < digits / 2; i++) {
    int t = d[digits - i - 1];
    d[digits - i - 1] = d[i];
    d[i] = t;
  }
  
  return digits;
}

int main(void) {
  int i;
  unsigned no;
  int cd;
  int dno;
  char cno[512];
  int retry;

  puts("10進数を基数変換します。");

  do {
    printf("変換する非負の整数 : ");
    scanf("%u", &no);

    do {
      printf("何進数に変換しますか(2-36) : ");
      scanf("%d", &cd);
    } while(cd < 2 || cd > 36);

    dno = card_convr(no, cd, cno);

    printf("%d進数では", cd);
    for(i = 0; i < dno; i++)
      printf("%c", cno[i]);
    printf("です。\n");

    printf("もう一度しますか(1···はい/0···いいえ) : ");
    scanf("%d", &retry);
    
  } while(retry == 1);
  
  return 0;
}




#include <stdio.h>

void ary_copy(int a[], const int b[], int n) {
  int i;
  for(i = 0; i < n; i++) {
    a[i] = b[i];
  }
}

int main(void) {
  int a[] = {0,0,0,0,0};
  int b[] = {1,2,3,4,5};
  int i;
  
  ary_copy(a, b, 5);

  for(i = 0; i < 5; i++) {
    printf("a[%d] = %d\n", i, a[i]);
  }
  
  return 0;
}




#include <stdio.h>

void ary_rcopy(int a[], const int b[], int n) {
  int i;
  for(i = 0; i < n; i++) {
    a[i] = b[n - i - 1];
  }
}

int main(void) {
  int a[] = {0,0,0,0,0};
  int b[] = {1,2,3,4,5};
  int i;
  
  ary_rcopy(a, b, 5);

  for(i = 0; i < 5; i++) {
    printf("a[%d] = %d\n", i, a[i]);
  }
  
  return 0;
}





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

void shuffle(int a[], int n) {
  int i,j;
  srand(time(NULL));
  for(i = 0; i < n; i++) {
    j = rand() % n;
    int t = a[j];
    a[j] = a[i];
    a[i] = t;
  }
}

int main(void) {
  int a[] = {1,2,3,4,5};
  int i;

  shuffle(a, 5);

  for(i = 0; i < 5; i++) {
    printf("a[%d] = %d\n", i, a[i]);
  }
  
  return 0;
}





#include <stdio.h>

int mdays[][12] = {
  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};

int isLeap(int year) {
  return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

int dayofyear(int y, int m, int d) {
  m--;
  while(m) {
    d += mdays[isLeap(y)][m - 1];
    m--;
  }
  return d;
}

int main(void) {
  int year, month, day;
  int retry;

  do {
    printf("年 : "); scanf("%d", &year);
    printf("月 : "); scanf("%d", &month);
    printf("日 : "); scanf("%d", &day);
    printf("年内で%d日目です。\n", dayofyear(year, month, day));
    printf("もう一度しますか(1···はい/0···いいえ) : ");
    scanf("%d", &retry);
  } while (retry == 1);
  
  return 0;
}