函数read_new_int

时间:2018-11-22 17:21:01

标签: c arrays pointers input

我的程序应该是5个选项的菜单。首先,它应该为变量“ n”分配一个新值,但是当我在输入中输入选项0时,然后我插入1作为下一个选项,这会从MSB中写入整数“ n”的二进制表示形式,我发现“ n”与我在程序开始时在输入中写的值相同。我真的找不到发生了什么事。

#include <stdio.h> 
#define DIM_F 4
#define DIM 31

// This is a function which reads an integer from input //
void read_new_int(int n); 
// This is a function that prints the binary representation of integer n
void print_bin_msb(int n);
// This is a function that calculates the opposite of a binary number and converts it into decimal
void calc_opp_dec(int n); 
// This function prints the opposite binary of an integer read in input
void print_opp_bin_msb(int n); 

int main(void) {
  void (*f[DIM_F])(
      int) = {read_new_int , print_bin_msb, calc_opp_dec , print_opp_bin_msb};
  int n;
  int choice_option;
  printf("Insert a positive integer");
  while (scanf("%d", &n) != 1) {
    printf("Insert a positive integer\n ");
    while (getchar() != '\n')
      ;
  }

  do {
    printf("0: Read new integer n\n1: print the binary representation of integer n\n2: Calcolate the opposite of the last integer and printing it as a decimal\n3: Calcolate the opposite of an integer\n4: Print the binary representation of the opposite of the last integer\n5: End of the program\n");
    printf("Which option would you choose?");
    while (scanf("%d", &choice_option) != 1 && choice_option < 4
        && choice_option >= 0) {
      printf("Insert a new integer: ");
      while (getchar() != '\n')
        ;
    }
    if (choice_option < 4 && choice_option >= 0) {
      (*f[choice_option])(n);
    } else {
      printf("CIAO - programma terminato\n");
    }
  } while (choice_option < 4 && choice_option >= 0);
  return 0;
}

void calc_bin(int choice, int n) {
  int i;
  int arr[DIM];
  for (i = 0; i < DIM; i++) {
    if (n % 2 == 0)
      arr[i] = 0;
    else {
      arr[i] = 1;
    }
    n = n / 2;
  }

}

void read_new_int(int x) {
  while (scanf("%d", &n) != 1) {
    printf("Insert a positive integer\n ");
    while (getchar() != '\n')
      ;
  }
}

void print_bin_msb(int n) {
  int i;
  int temp = 0;
  int temp_1 = n;
  int tempa = n;
  while (!(temp_1 == 0)) {
    temp = temp + 1;
    temp_1 = temp_1 / 2;
  }
  if (n >= 0) {
    printf("0");
  } else {
    printf("1");
  }
  for (i = 0; i < DIM - temp; i++) {
    printf("0");

  }
  do {
    if (tempa % 2 == 0) {
      printf("0");
    } else {
      printf("1");
    }
    tempa = tempa / 2;
  } while (tempa != 0);

  printf("\n");
}

0 个答案:

没有答案