1. 함수 형식 - 입력받은 배열 역순 정렬
형 변환 필수!!!!!!!!!!! (int *)
int *pVal = (int*)malloc(sizeof(int));
#include <iostream>
#include <stdlib.h>
#include <algorithm> // swap
#include <vector>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
#define swap(type, x,y) do{type t=x;x=y;y=t;} while(0)
void ary_reverse(int a[], int n){
for(int i=0;i<n/2;i++) // 역순으로 정렬(요소 개수가 n인 배열 a의 요소를 역순으로 정렬
swap(int, a[i], a[n-i-1]);
}
int main(void){
int i;
int *x;
int nx;
cout <<"요소 개수 : ";
cin>>nx;
x=(int *)calloc(nx, sizeof(int)); // 요소 개수가 nx인 int형 배열 x를 생성
cout <<nx<<"개의 정수를 입력하시오."<<endl;
for(i=0;i<nx;i++){
cout <<"x["<<i<<"] : ";
cin>>x[i];
}
ary_reverse(x, nx); // 배열 x 역순 정렬
cout<<"배열의 요소를 역순으로 정렬함"<<endl;
for(i=0;i<nx;i++){
cout <<"x["<<i<<"] = "<<x[i]<<endl;
}
free(x);
return 0;
}
블록을 do문으로 둘러싸는 경우
#define swap(type, x,y) do{type t=x;x=y;y=t;} while(0)
if(a>b)
do{type t=a; a=b; b=t;} while(0);
else
do{type t=a; a=c; c=t;} while(0);
2. 기수 변환
#include <iostream>
#include <cstdio>
using namespace std;
// 정수 값 x를 n진수로 변환하여 배열 d에 아랫자리부터 저장
int card_convr(unsigned x, int n, char d[]){
char dchar[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int digits = 0;//변환 후 자릿수
if(x==0){
d[digits++] =dchar[0];//변환 후에도 0
}
else{
while(x){
d[digits++] = dchar[x%n]; //n으로 나눈 나머지 저장
x/=n;
}
}
return digits;
}
int main(void){
int i;
unsigned num;// 변환하는 정수;
int cardinal_n; // 기수
int dcnt; // 변환 후 자릿수
char cardinal_num[512];// 변환한 값의 각 자리 숫자를 저장하는 문자 배열
int retry;// 한번 더
puts("10진수를 기수 변환한다. ");
do{
puts("변환하는 음이 아닌 정수 : ");
cin>> num;
do{
puts("어떤 진수로 변환할까요?(2-36) : ");
cin>>cardinal_n;
}while(cardinal_n<2||cardinal_n>36);
dcnt = card_convr(num, cardinal_n,cardinal_num);
cout <<cardinal_n<<"진수로는";
for(i=dcnt-1;i>=0;i--){ // dnltwkfl qnxj ckfPfh cnffur
cout <<cardinal_num[i];
}
puts("입니다.");
cout<<"한번 더 할까요?(1=예/0=아니요) : ";
cin>>retry;
}while(retry==1); // 다시 do ~ while 문 돈다
return 0;
}
puts()
:: only string만 출력 (줄바꿈 포함)
gets(), gets_s()//권장
:: string만 입력받을 수 있음 (개행을 기준으로 입력 받음)
1. 사용자로부터 문자열을 입력받아 함수의 인자로 명시한 주소의 메모리에 저장
2. 입출력 버퍼가 비어있는지 확인하고 비어있다면 문자열을 입력받아 입출력 버퍼에 저장
✅ c++ 함수들 정리한 사이트!
https://www.programiz.com/cpp-programming/library-function/cstdio/gets
C++ gets() - C++ Standard Library
C++ gets() The gets() function in C++ reads characters from stdin and stores them until a newline character is found or end of file occurs. gets() prototype char* gets(char* str); The gets() function reads characters from stdin and stores them in str until
www.programiz.com
'코딩 > C++' 카테고리의 다른 글
C++ 알고리즘 연습문제 - 함수사용, 윤년계산 (0) | 2022.03.23 |
---|---|
C++ 알고리즘 연습문제 - 함수사용 (0) | 2022.03.22 |
백준 문제풀이 C++ [220303] - 브루트 포스, pair<type, type> (0) | 2022.03.03 |
백준 문제풀이 C++ [220226] - 정렬 (0) | 2022.02.26 |
백준 문제풀이 C++ [220226] - 브루트 포스 (0) | 2022.02.26 |