결과 출력
이 마지막 단계에서는 벡터 연산 프로그램을 개선하여 형식화된 출력을 추가하고 벡터 결과를 명확하고 읽기 쉽게 출력하는 함수를 만듭니다.
vector_operations.c 파일을 다음 개선된 구현으로 업데이트합니다.
cd ~/project
nano vector_operations.c
새로운 출력 함수를 추가하고 메인 프로그램을 수정합니다.
#include <stdio.h>
#define VECTOR_SIZE 3
void readVector(float vector[], int size) {
printf("Enter %d vector components (separated by space): ", size);
for (int i = 0; i < size; i++) {
scanf("%f", &vector[i]);
}
}
float computeDotProduct(float vector1[], float vector2[], int size) {
float dotProduct = 0.0;
for (int i = 0; i < size; i++) {
dotProduct += vector1[i] * vector2[i];
}
return dotProduct;
}
void computeCrossProduct(float vector1[], float vector2[], float result[]) {
result[0] = vector1[1] * vector2[2] - vector1[2] * vector2[1];
result[1] = vector1[2] * vector2[0] - vector1[0] * vector2[2];
result[2] = vector1[0] * vector2[1] - vector1[1] * vector2[0];
}
// 벡터를 형식화하여 출력하는 새로운 함수
void printVector(const char* label, float vector[], int size) {
printf("%s: [", label);
for (int i = 0; i < size; i++) {
printf("%.2f%s", vector[i], (i < size - 1) ? ", " : "");
}
printf("]\n");
}
int main() {
float vector1[VECTOR_SIZE];
float vector2[VECTOR_SIZE];
float crossProductResult[VECTOR_SIZE];
// 벡터 입력
printf("Vector Input:\n");
printVector("Vector 1", vector1, VECTOR_SIZE);
readVector(vector1, VECTOR_SIZE);
printVector("Vector 2", vector2, VECTOR_SIZE);
readVector(vector2, VECTOR_SIZE);
// 결과 계산
float dotProduct = computeDotProduct(vector1, vector2, VECTOR_SIZE);
computeCrossProduct(vector1, vector2, crossProductResult);
// 형식화된 결과 출력
printf("\nVector Operations Results:\n");
printVector("Vector 1", vector1, VECTOR_SIZE);
printVector("Vector 2", vector2, VECTOR_SIZE);
printf("Dot Product: %.2f\n", dotProduct);
printVector("Cross Product", crossProductResult, VECTOR_SIZE);
return 0;
}
업데이트된 프로그램을 컴파일하고 실행합니다.
gcc vector_operations.c -o vector_operations
./vector_operations
예시 출력:
Vector Input:
Vector 1: [0.00, 0.00, 0.00]
Enter 3 vector components (separated by space): 1 2 3
Vector 2: [0.00, 0.00, 0.00]
Enter 3 vector components (separated by space): 4 5 6
Vector Operations Results:
Vector 1: [1.00, 2.00, 3.00]
Vector 2: [4.00, 5.00, 6.00]
Dot Product: 32.00
Cross Product: [-3.00, 6.00, -3.00]
설명
- 일관되고 형식화된 벡터 출력을 생성하는
printVector() 함수를 추가했습니다.
- 벡터 입력 및 결과 출력을 보여주는
main() 함수를 개선했습니다.
- 벡터 및 계산 결과의 가독성을 높였습니다.
- 벡터 연산 결과를 깔끔하고 전문적인 형식으로 제공합니다.