更新我的作業

This commit is contained in:
JEFF 2025-01-20 21:30:53 +08:00
parent 366c9cee22
commit 356bd074d2
333 changed files with 19441 additions and 425 deletions

Binary file not shown.

BIN
作業/exam/exam.zip Normal file

Binary file not shown.

264
作業/exam/exam/exam_1.cpp Normal file
View File

@ -0,0 +1,264 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct node {
int coef;
int exp;
int root;
struct node* rlink;
struct node* llink;
} node;
node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root;
void init_f() {
head = (node *)malloc(sizeof(node));
tail = (node *)malloc(sizeof(node));
head->rlink = tail;
tail->llink = head;
head_root = (node *)malloc(sizeof(node));
tail_root = (node *)malloc(sizeof(node));
head_root->rlink = tail_root;
tail_root->llink = head_root;
}
void read_poly(char str[] ){
int argCount ;
while (1) {
node* newNode = (node*)malloc(sizeof(node));
argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str);
if (argCount >= 2) { // 成功讀取係數和指數
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
if (argCount == 2) {
break ;
}
} else {
if(!isdigit(newNode->coef)){
newNode->exp = 0;
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
break ;
}else{
// printf("newNode->coef = %d\n",newNode->coef);
// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef));
free(newNode);
break ;
}
}
}
}
void compact(char str[]){ /* 移除str當中的空白使變得緊實 */
int i, j;
for (i = j = 0; str[i]; i++, j++) {
for (; str[i]==' '; i++);
str[j] = str[i];
}
str[j] = '\0';
printf("\n移除空白後的字串:%s",str);
}
void clear_node(){
// 釋放記憶體
current = head->rlink;
while (current != tail) {
temp = current;
current = current->rlink;
free(temp);
}
current_root = head_root->rlink;
while (current_root != tail_root) {
temp = current_root;
current_root = current_root->rlink;
free(temp);
}
free(head);
free(tail);
free(head_root);
free(tail_root);
}
void show( int n, int mode){
int i;
if(mode == 0){
printf("\n方程式p(x)= ");
current = head->rlink;
while (current != tail) {
if(abs(current->coef)>1){
printf("%s%d", current->coef > 1? "":"\b",current->coef);
}else if(current->coef == -1){
printf("%s", current->exp == 0? "\b-1":"\b-");
}
switch(current->exp){
case 0:
if(current->coef == 1 ) printf("1+");
else printf("+");
break;
case 1:
printf("x+");
break;
default:
printf("x^%d+",current->exp);
}
current = current->rlink;
}
printf("\b ");
}else { /* mode==1顯示所得解 */
current_root = head_root->rlink;
while(current_root != tail_root){
printf("%d ",current_root->root);
current_root = current_root->rlink;
}
}
}
int findRoot() /* 找根所得解存入q[],回傳根的個數 */
{
current_root = head_root->rlink;
int r, c = 0, i, j, k, sum;
int sign[2] = {1,-1};
current = tail->llink;
r = abs(current->coef); /* 取出最低階項之係數 */
if (current->exp != 0) { /* 最低階項的指數 >= 1則0為可能解 */
if ((i = current->exp) > 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = 0; /* 最低階項的指數設為i */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
current = head->rlink;
while(current!=tail){
current->exp -= i; /* 所有項次的指數減去i */
current = current->rlink;
}
}
// r = abs(p[2*p[0]]); /* 取出最低階項之係數 */
for (i = 1; i <= r; i++) { /* 考慮能整除r的因數i須注意正負號 */
if (r%i != 0) continue; /* 不能整除r的i將略過繼續考慮下一個i */
for (j = 0; j < 2; j++) { /* j為0代表考慮+i的情境j為1代表考慮-i的情況 */
for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* 計算每一項的結果值(係數*x^指數)並累加到sum之中 */
sum += current->coef *(int)(pow(sign[j]*i,current->exp));
if (sum == 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = sign[j]*i; /* bingo! 發現合乎條件的整數根將其寫入q陣列 */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
}
}
return c;
}
void sort(){
//若沒有資料或只有一筆資料
if (head->rlink == tail || head->rlink->rlink == tail) {
return;
}
int flag = 1;
while(flag){
flag = 0;
current = head->rlink;
while(current->rlink != tail){
temp = current->rlink;
if(current->exp < temp->exp ){
temp->llink = current->llink;
current->rlink = temp->rlink;
temp->rlink->llink = current;
temp->rlink = current;
current->llink->rlink = temp;
current->llink = temp;
flag = 1;
}
else{
current = current->rlink;
}
}
}
}
int main() {
char str[100];
int poly_num ,c , high;
init_f();
printf("\n*** 解多項式之整數根 ***\n\n輸入多項式 ==> ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("輸入錯誤!\n");
return 1;
}
compact(str);
read_poly(str);
sort();
current = head->rlink;
high= current->exp;
show(c,0);
c = findRoot();
if (c > 0) {
printf("\n\n解得整數根為:");
show(c,1);
}
else
printf("\n\n整數根不存在\n");
clear_node();
return 0;
}

290
作業/exam/exam/exam_2.cpp Normal file
View File

@ -0,0 +1,290 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#define MAX 100
// === 全域變數宣告 ===
char input[MAX];
char postfix[MAX];
char postfix_1[MAX]; //顯示用
char stack[MAX];
double numStack[MAX];
int top = -1;
int numTop = -1;
// === 函式宣告 ===
int get_priority(char op);
int is_operator(char c);
double calculate(double a, double b, char op);
void convert_to_postfix();
double evaluate_postfix();
double evaluate_infix(char *expr);
double parse_number(char **expr);
int get_priority(char c){
if(c=='+' || c=='-'){
return 1;
}else if(c=='*' || c=='/' || c=='%' ){
return 2;
}else if(c=='^' || c=='s' || c=='c' ){
return 3;
}else{
return 0;
}
}
// === 檢查字元是否為運算子 ===
int is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%' ||c == 's' || c == 'c');
}
// === 執行運算 ===
double calculate(double a, double b, char op) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if(b != 0) return a / b;
printf("錯誤:除數不能為零!\n");
exit(1);
case '^': return pow(a, b);
case '%': return (int)a % (int)b;
case 's': return sin(b);
case 'c': return cos(b);
default: return 0;
}
}
//顯示用
void convert_to_postfix_forprint() {
int i = 0, j;
int postfix_index = 0;
top = -1;
char number_str[MAX];
int is_negative;
while(input[i] != '\0') {
if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) {
// 處理數字(包括負數)
is_negative = 0;
int num_len = 0;
// 檢查是否為負數
if(input[i] == '-') {
is_negative = 1;
i++;
}
// 收集完整數字字串
while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) {
number_str[num_len++] = input[i++];
}
number_str[num_len] = '\0';
i--; // 回退一個位置,因為外層 while 會再加一
// 輸出數字
printf("%s ", number_str);
if(is_negative) {
printf("- ");
}
// 將數字加入後序表達式
for(j = 0; j < num_len; j++) {
postfix_1[postfix_index++] = number_str[j];
}
postfix_1[postfix_index++] = ' ';
if(is_negative) {
postfix_1[postfix_index++] = '-';
postfix_1[postfix_index++] = ' ';
}
}
else if(input[i] == '(') {
stack[++top] = input[i];
}
else if(input[i] == ')') {
while(top >= 0 && stack[top] != '(') {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
if(top >= 0) top--;
}
else if(is_operator(input[i])) {
// 如果不是處理負數的減號
if(input[i-1] != 'o'){
if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) {
while(top >= 0 && stack[top] != '(' &&
(get_priority(stack[top]) > get_priority(input[i]) ||
(get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
stack[++top] = input[i];
}
}
}
i++;
}
while(top >= 0) {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
postfix_1[postfix_index] = '\0';
printf("\n");
}
// === 轉換為後序表達式 ===
//計算用
void convert_to_postfix() {
int i = 0 , j;
int postfix_index = 0;
top = -1;
while(input[i] != '\0') {
if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { // 檢查是否為數字、小數點或是負號(且是表達式的開始,或緊跟在左括號或運算符後面)
char *end;
double num = strtod(&input[i], &end); //strtod 把字串換成浮點數
int len = end - &input[i]; //計算數字字串的長度 數字末端的記憶體位址減掉首項的記憶體位置
// printf("%.1f ", num);
for(j = 0; j < len; j++) {
postfix[postfix_index++] = input[i+j];
}
postfix[postfix_index++] = ' ';
i += len - 1;
}
else if(input[i] == '(') {
stack[++top] = input[i];
}
else if(input[i] == ')') {
while(top >= 0 && stack[top] != '(') {
// printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}
if(top >= 0) top--;
}
else if(is_operator(input[i])) {
if(input[i-1]!='o'){
while(top >= 0 && stack[top] != '(' && (get_priority(stack[top]) > get_priority(input[i]) || (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) {
// printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}
stack[++top] = input[i];
}
}
i++;
}
while(top >= 0) {
// printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}
postfix[postfix_index] = '\0';
// printf("\n");
}
// === 計算後序表達式 ===
double evaluate_postfix() {
int i;
numTop = -1;
char *token = strtok(postfix, " ");
// printf("\n計算過程\n");
while(token != NULL) {
// printf("處理標記:'%s'\n", token);
if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) {
double num = atof(token);
numStack[++numTop] = num;
// printf("壓入數字:%.2f\n", num);
}else if(token[0] == 's'|| token[0] == 'c' ){
if(numTop < 1) {
// printf("運算子 '%c' 缺少足夠的運算元\n", token[0]);
exit(1);
}
double b = numStack[numTop--];
double result = calculate(0, b, token[0]);
numStack[++numTop] = result;
// printf("計算:%c %.2f = %.4f\n", token[0], b, result);
}else if(is_operator(token[0])) {
if(numTop < 1) {
// printf("運算子 '%c' 缺少足夠的運算元\n", token[0]);
exit(1);
}
double b = numStack[numTop--];
double a = numStack[numTop--];
double result = calculate(a, b, token[0]);
numStack[++numTop] = result;
// printf("計算:%.2f %c %.2f = %.4f\n", a, token[0], b, result);
}
else {
// printf("錯誤:未知的標記 '%s'\n", token);
exit(1);
}
// printf("當前堆疊:");
for(i = 0; i <= numTop; i++) {
// printf("%.2f ", numStack[i]);
}
// printf("\n\n");
token = strtok(NULL, " ");
}
if(numTop != 0) {
// printf("錯誤:計算結束後堆疊中剩餘 %d 個元素\n", numTop + 1);
exit(1);
}
return numStack[numTop];
}
int main() {
printf("請輸入中序表示式(支援+-*/%^()運算) => ");
fgets(input, MAX, stdin);
input[strcspn(input, "\n")] = 0;
printf("\n對應的後序表示法式: ");
convert_to_postfix_forprint(); //顯示用
// printf("\n計算的後序表示法式 ");
convert_to_postfix();
double postfix_result = evaluate_postfix();
printf("\n運算結果:%.4f", postfix_result);
printf("\t(正確值為:");
if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){
printf("%g",10+20*(50-30)/pow(2,4)-6*8);
}else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){
printf("%g",10+20*(-50+30)/pow(-2,4)-6*8);
}else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){
printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2);
}else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){
printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2);
}else if(strcmp(input,"10-30*(-40-20)%2^4+7.5*-6")==0){
printf("%g",10-30*(-40-20)%(int)pow(2,4)+7.5*-6);
}else if(strcmp(input,"1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)")==0){
printf("%g",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*(int)pow(2,-2.5))*cos(123.456));
}printf(")");
return 0;
}

264
作業/exam/exam_1.cpp Normal file
View File

@ -0,0 +1,264 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct node {
int coef;
int exp;
int root;
struct node* rlink;
struct node* llink;
} node;
node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root;
void init_f() {
head = (node *)malloc(sizeof(node));
tail = (node *)malloc(sizeof(node));
head->rlink = tail;
tail->llink = head;
head_root = (node *)malloc(sizeof(node));
tail_root = (node *)malloc(sizeof(node));
head_root->rlink = tail_root;
tail_root->llink = head_root;
}
void read_poly(char str[] ){
int argCount ;
while (1) {
node* newNode = (node*)malloc(sizeof(node));
argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str);
if (argCount >= 2) { // 成功讀取係數和指數
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
if (argCount == 2) {
break ;
}
} else {
if(!isdigit(newNode->coef)){
newNode->exp = 0;
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
break ;
}else{
// printf("newNode->coef = %d\n",newNode->coef);
// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef));
free(newNode);
break ;
}
}
}
}
void compact(char str[]){ /* 移除str當中的空白使變得緊實 */
int i, j;
for (i = j = 0; str[i]; i++, j++) {
for (; str[i]==' '; i++);
str[j] = str[i];
}
str[j] = '\0';
printf("\n移除空白後的字串:%s",str);
}
void clear_node(){
// 釋放記憶體
current = head->rlink;
while (current != tail) {
temp = current;
current = current->rlink;
free(temp);
}
current_root = head_root->rlink;
while (current_root != tail_root) {
temp = current_root;
current_root = current_root->rlink;
free(temp);
}
free(head);
free(tail);
free(head_root);
free(tail_root);
}
void show( int n, int mode){
int i;
if(mode == 0){
printf("\n方程式p(x)= ");
current = head->rlink;
while (current != tail) {
if(abs(current->coef)>1){
printf("%s%d", current->coef > 1? "":"\b",current->coef);
}else if(current->coef == -1){
printf("%s", current->exp == 0? "\b-1":"\b-");
}
switch(current->exp){
case 0:
if(current->coef == 1 ) printf("1+");
else printf("+");
break;
case 1:
printf("x+");
break;
default:
printf("x^%d+",current->exp);
}
current = current->rlink;
}
printf("\b ");
}else { /* mode==1顯示所得解 */
current_root = head_root->rlink;
while(current_root != tail_root){
printf("%d ",current_root->root);
current_root = current_root->rlink;
}
}
}
int findRoot() /* 找根所得解存入q[],回傳根的個數 */
{
current_root = head_root->rlink;
int r, c = 0, i, j, k, sum;
int sign[2] = {1,-1};
current = tail->llink;
r = abs(current->coef); /* 取出最低階項之係數 */
if (current->exp != 0) { /* 最低階項的指數 >= 1則0為可能解 */
if ((i = current->exp) > 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = 0; /* 最低階項的指數設為i */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
current = head->rlink;
while(current!=tail){
current->exp -= i; /* 所有項次的指數減去i */
current = current->rlink;
}
}
// r = abs(p[2*p[0]]); /* 取出最低階項之係數 */
for (i = 1; i <= r; i++) { /* 考慮能整除r的因數i須注意正負號 */
if (r%i != 0) continue; /* 不能整除r的i將略過繼續考慮下一個i */
for (j = 0; j < 2; j++) { /* j為0代表考慮+i的情境j為1代表考慮-i的情況 */
for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* 計算每一項的結果值(係數*x^指數)並累加到sum之中 */
sum += current->coef *(int)(pow(sign[j]*i,current->exp));
if (sum == 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = sign[j]*i; /* bingo! 發現合乎條件的整數根將其寫入q陣列 */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
}
}
return c;
}
void sort(){
//若沒有資料或只有一筆資料
if (head->rlink == tail || head->rlink->rlink == tail) {
return;
}
int flag = 1;
while(flag){
flag = 0;
current = head->rlink;
while(current->rlink != tail){
temp = current->rlink;
if(current->exp < temp->exp ){
temp->llink = current->llink;
current->rlink = temp->rlink;
temp->rlink->llink = current;
temp->rlink = current;
current->llink->rlink = temp;
current->llink = temp;
flag = 1;
}
else{
current = current->rlink;
}
}
}
}
int main() {
char str[100];
int poly_num ,c , high;
init_f();
printf("\n*** 解多項式之整數根 ***\n\n輸入多項式 ==> ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("輸入錯誤!\n");
return 1;
}
compact(str);
read_poly(str);
sort();
current = head->rlink;
high= current->exp;
show(c,0);
c = findRoot();
if (c > 0) {
printf("\n\n解得整數根為:");
show(c,1);
}
else
printf("\n\n整數根不存在\n");
clear_node();
return 0;
}

BIN
作業/exam/exam_1.exe Normal file

Binary file not shown.

296
作業/exam/exam_2.cpp Normal file
View File

@ -0,0 +1,296 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#define MAX 100
// === 全域變數宣告 ===
char input[MAX];
char postfix[MAX];
char postfix_1[MAX]; //顯示用
char stack[MAX];
double numStack[MAX];
int top = -1;
int numTop = -1;
// === 函式宣告 ===
int get_priority(char op);
int is_operator(char c);
double calculate(double a, double b, char op);
void convert_to_postfix();
double evaluate_postfix();
double evaluate_infix(char *expr);
double parse_number(char **expr);
int get_priority(char c){
if(c=='+' || c=='-'){
return 1;
}else if(c=='*' || c=='/' || c=='%' ){
return 2;
}else if(c=='^' || c=='s' || c=='c' ){
return 3;
}else{
return 0;
}
}
// === 檢查字元是否為運算子 ===
int is_operator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%' ||c == 's' || c == 'c');
}
// === 執行運算 ===
double calculate(double a, double b, char op) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if(b != 0) return a / b;
printf("錯誤:除數不能為零!\n");
exit(1);
case '^': return pow(a, b);
case '%': return (int)a % (int)b;
case 's': return sin(b);
case 'c': return cos(b);
default: return 0;
}
}
//顯示用
void convert_to_postfix_forprint() {
int i = 0, j;
int postfix_index = 0;
top = -1;
char number_str[MAX];
int is_negative;
while(input[i] != '\0') {
if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) {
// 處理數字(包括負數)
is_negative = 0;
int num_len = 0;
// 檢查是否為負數
if(input[i] == '-') {
is_negative = 1;
i++;
}
// 收集完整數字字串
while(input[i] != '\0' && (isdigit(input[i]) || input[i] == '.')) {
number_str[num_len++] = input[i++];
}
number_str[num_len] = '\0';
i--; // 回退一個位置,因為外層 while 會再加一
// 輸出數字
printf("%s ", number_str);
if(is_negative) {
printf("- ");
}
// 將數字加入後序表達式
for(j = 0; j < num_len; j++) {
postfix_1[postfix_index++] = number_str[j];
}
postfix_1[postfix_index++] = ' ';
if(is_negative) {
postfix_1[postfix_index++] = '-';
postfix_1[postfix_index++] = ' ';
}
}
else if(input[i] == '(') {
stack[++top] = input[i];
}
else if(input[i] == ')') {
while(top >= 0 && stack[top] != '(') {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
if(top >= 0) top--;
}
else if(is_operator(input[i])) {
// 如果不是處理負數的減號
if(input[i] == '+' && input[i-1] == '('){
}
else if(input[i-1] != 'o'){
if(!(input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) {
while(top >= 0 && stack[top] != '(' &&
(get_priority(stack[top]) > get_priority(input[i]) ||
(get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
stack[++top] = input[i];
}
}
}
i++;
}
while(top >= 0) {
printf("%c ", stack[top]);
postfix_1[postfix_index++] = stack[top];
postfix_1[postfix_index++] = ' ';
top--;
}
postfix_1[postfix_index] = '\0';
printf("\n");
}
// === 轉換為後序表達式 ===
//計算用
void convert_to_postfix() {
int i = 0 , j;
int postfix_index = 0;
top = -1;
while(input[i] != '\0') {
if(isdigit(input[i]) || input[i] == '.' || (input[i] == '-' && (i == 0 || input[i-1] == '(' || is_operator(input[i-1])))) { // 檢查是否為數字、小數點或是負號(且是表達式的開始,或緊跟在左括號或運算符後面)
char *end;
double num = strtod(&input[i], &end); //strtod 把字串換成浮點數
int len = end - &input[i]; //計算數字字串的長度 數字末端的記憶體位址減掉首項的記憶體位置
printf("%.1f ", num);
for(j = 0; j < len; j++) {
postfix[postfix_index++] = input[i+j];
}
postfix[postfix_index++] = ' ';
i += len - 1;
}else if(input[i] == '(') {
stack[++top] = input[i];
}
else if(input[i] == ')') {
while(top >= 0 && stack[top] != '(') {
printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}if(top >= 0) top--;
}else if(is_operator(input[i])) {
if(input[i] == '+' && input[i-1] == '('){
}else if(input[i-1]!='o' ){
while(top >= 0 && stack[top] != '(' && (get_priority(stack[top]) > get_priority(input[i]) || (get_priority(stack[top]) == get_priority(input[i]) && input[i] != '^'))) {
printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}
stack[++top] = input[i];
}
}
i++;
}
while(top >= 0) {
printf("%c ", stack[top]);
postfix[postfix_index++] = stack[top];
postfix[postfix_index++] = ' ';
top--;
}
postfix[postfix_index] = '\0';
printf("\n");
}
// === 計算後序表達式 ===
double evaluate_postfix() {
int i;
numTop = -1;
char *token = strtok(postfix, " ");
printf("\n計算過程:\n");
while(token != NULL) {
printf("處理標記:'%s'\n", token);
if(isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) {
double num = atof(token);
numStack[++numTop] = num;
printf("壓入數字:%.2f\n", num);
}else if(token[0] == 's'|| token[0] == 'c' ){
if(numTop < 1) {
printf("運算子 '%c' 缺少足夠的運算元\n", token[0]);
exit(1);
}
double b = numStack[numTop--];
double result = calculate(0, b, token[0]);
numStack[++numTop] = result;
printf("計算:%c %.2f = %.2f\n", token[0], b, result);
}else if(is_operator(token[0])) {
if(numTop < 1) {
printf("運算子 '%c' 缺少足夠的運算元\n", token[0]);
exit(1);
}
double b = numStack[numTop--];
double a = numStack[numTop--];
double result = calculate(a, b, token[0]);
numStack[++numTop] = result;
printf("計算:%.2f %c %.2f = %.2f\n", a, token[0], b, result);
}
else {
printf("錯誤:未知的標記 '%s'\n", token);
exit(1);
}
printf("當前堆疊:");
for(i = 0; i <= numTop; i++) {
printf("%.2f ", numStack[i]);
}
printf("\n\n");
token = strtok(NULL, " ");
}
if(numTop != 0) {
printf("錯誤:計算結束後堆疊中剩餘 %d 個元素\n", numTop + 1);
exit(1);
}
return numStack[numTop];
}
int main() {
printf("請輸入中序表示式(支援+-*/%^()運算) => ");
fgets(input, MAX, stdin);
input[strcspn(input, "\n")] = 0;
printf("\n對應的後序表示法式: ");
convert_to_postfix_forprint(); //顯示用
printf("\n計算的後序表示法式: ");
convert_to_postfix();
double postfix_result = evaluate_postfix();
printf("\n運算結果:%.4f", postfix_result);
printf("\t(正確值為:");
if(strcmp(input,"10+20*(50-30)/2^4-6*8")==0){
printf("%g",10+20*(50-30)/pow(2,4)-6*8);
}else if(strcmp(input,"10+20*(-50+30)/-2^4-6*8")==0){
printf("%g",10+20*(-50+30)/pow(-2,4)-6*8);
}else if(strcmp(input,"10.5+20.8*(50.1-30.6)/2.5^4-6.6*8.2")==0){
printf("%g",10.5+20.8*(50.1-30.6)/pow(2.5,4)-6.6*8.2);
}else if(strcmp(input,"10.5+20.8*(-50.1+30.6)/2.5^-4-6.6*8.2")==0){
printf("%g",10.5+20.8*(-50.1+30.6)/pow(2.5,-4)-6.6*8.2);
}else if(strcmp(input,"10-30*(-40-20)%2^4+7.5*-6")==0){
printf("%g",10-30*(-40-20)%(int)pow(2,4)+7.5*-6);
}else if(strcmp(input,"1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)")==0){
printf("%g",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2,-2.5))*cos(123.456));
}else if(strcmp(input,"100*(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*(50/30.0)^3.5-6*8)))^2")==0){
printf("%g",100*pow(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*pow(50/30.0,3.5)-6*8)),2));
}else if(strcmp(input,"100*(sin(sin(sin(+50.2*cos((30+100%40)*sin(60/5.5)))+20*(+50/30.0)^3.5-6*8)))^2")==0){
printf("%g",100*pow(sin(sin(sin(50.2*cos((30+100%40)*sin(60/5.5)))+20*pow(50/30.0,3.5)-6*8)),2));
}printf(")");
return 0;
}

BIN
作業/exam/exam_2.exe Normal file

Binary file not shown.

266
作業/exam/main.cpp Normal file
View File

@ -0,0 +1,266 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct node {
int coef;
int exp;
int root;
struct node* rlink;
struct node* llink;
} node;
node *head, *tail, *current, *prev, *temp ,*head_root , *current_root , *tail_root;
void init_f() {
head = (node *)malloc(sizeof(node));
tail = (node *)malloc(sizeof(node));
head->rlink = tail;
tail->llink = head;
head_root = (node *)malloc(sizeof(node));
tail_root = (node *)malloc(sizeof(node));
head_root->rlink = tail_root;
tail_root->llink = head_root;
}
void read_poly(char str[] ){
int argCount ;
while (1) {
node* newNode = (node*)malloc(sizeof(node));
argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str);
if (argCount >= 2) { // 成功讀取係數和指數
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
if (argCount == 2) {
break ;
}
} else {
if(!isdigit(newNode->coef)){
newNode->exp = 0;
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
break ;
}else{
// printf("newNode->coef = %d\n",newNode->coef);
// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef));
free(newNode);
break ;
}
}
}
}
void compact(char str[]){ /* 移除str當中的空白使變得緊實 */
int i, j;
for (i = j = 0; str[i]; i++, j++) {
for (; str[i]==' '; i++);
str[j] = str[i];
}
str[j] = '\0';
printf("\n移除空白後的字串:%s\n",str);
}
void clear_node(){
// 釋放記憶體
current = head->rlink;
while (current != tail) {
temp = current;
current = current->rlink;
free(temp);
}
free(head);
free(tail);
free(head_root);
free(tail_root);
}
void show( int n, int mode){
int i;
if(mode == 0){
printf("\n方程式p(x)= ");
current = head->rlink;
while (current != tail) {
if(abs(current->coef)>1){
printf("%s%d", current->coef > 1? "":"\b",current->coef);
}else if(current->coef == -1){
printf("%s", current->exp == 0? "\b-1":"\b-");
}
switch(current->exp){
case 0:
if(current->coef == 1 ) printf("1+");
else printf("+");
break;
case 1:
printf("x+");
break;
default:
printf("x^%d+",current->exp);
}
current = current->rlink;
}
printf("\b ");
}else { /* mode==1顯示所得解 */
current_root = head_root->rlink;
while(current_root != tail_root){
printf("%d ",current_root->root);
current_root = current_root->rlink;
}
}
}
int findRoot() /* 找根所得解存入q[],回傳根的個數 */
{
current_root = head_root->rlink;
int r, c = 0, i, j, k, sum;
int sign[2] = {1,-1};
current = tail->llink;
r = abs(current->coef); /* 取出最低階項之係數 */
if (current->exp != 0) { /* 最低階項的指數 >= 1則0為可能解 */
if ((i = current->exp) > 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = 0; /* 最低階項的指數設為i */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
current = head->rlink;
while(current!=tail){
current->exp -= i; /* 所有項次的指數減去i */
current = current->rlink;
}
}
// r = abs(p[2*p[0]]); /* 取出最低階項之係數 */
for (i = 1; i <= r; i++) { /* 考慮能整除r的因數i須注意正負號 */
if (r%i != 0) continue; /* 不能整除r的i將略過繼續考慮下一個i */
for (j = 0; j < 2; j++) { /* j為0代表考慮+i的情境j為1代表考慮-i的情況 */
for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* 計算每一項的結果值(係數*x^指數)並累加到sum之中 */
sum += current->coef *(int)(pow(sign[j]*i,current->exp));
if (sum == 0) {
node* newNode = (node*)malloc(sizeof(node));
newNode->root = sign[j]*i; /* bingo! 發現合乎條件的整數根將其寫入q陣列 */
newNode->llink = tail_root->llink;
newNode->rlink = tail_root;
tail_root->llink->rlink = newNode;
tail_root->llink = newNode;
c = 1;
}
}
}
return c;
}
void sort(){
//若沒有資料或只有一筆資料
if (head->rlink == tail || head->rlink->rlink == tail) {
return;
}
int flag = 1;
while(flag){
flag = 0;
current = head->rlink;
while(current->rlink != tail){
temp = current->rlink;
if(current->exp < temp->exp ){
temp->llink = current->llink;
current->rlink = temp->rlink;
temp->rlink->llink = current;
temp->rlink = current;
current->llink->rlink = temp;
current->llink = temp;
flag = 1;
}
else{
current = current->rlink;
}
}
}
}
int main() {
char str[100];
int poly_num ,c , high;
init_f();
printf("\n*** 解多項式之整數根 ***\n\n輸入多項式 ==> ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("輸入錯誤!\n");
return 1;
}
compact(str);
read_poly(str);
sort();
current = head->rlink;
high= current->exp;
show(c,0);
c = findRoot();
if (c > 0) {
printf("\n\n解得整數根為:");
show(c,1);
}
else
printf("\n\n整數根不存在\n");
clear_node();
return 0;
}

BIN
作業/exam/main.exe Normal file

Binary file not shown.

375
作業/test/DS4_test.cpp Normal file
View File

@ -0,0 +1,375 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>
#define MAX_NAME_LENGTH 24
//宣告函式原型
void init_f();
void readStudentsFromFile(char* filename);
void insertStudent(char* name, int english, int math);
void printStudentList();
void sort(int mode , int target);
void modify_list();
void add_data(char* name, int english, int math);
void remove_data(char* name);
void choose_subject();
// 定義學生節點結構
typedef struct Student {
char name[MAX_NAME_LENGTH];
int english;
int math;
struct Student* llink;
struct Student* rlink;
} Student;
Student *head, *tail, *current, *prev, *temp ,**arr;
FILE* file;
int list_length ;
void init_f() {
head = (Student *) malloc(sizeof(Student));
tail = (Student *) malloc(sizeof(Student));
// head->llink = head; // 左鏈結指向自己
// head->rlink = head; // 右鏈結指向自己
// tail = head;
// head->llink = tail;
head->rlink = tail;
// tail->rlink = head;
tail->llink = head;
}
// 在尾部插入新學生節點
void insertStudent(char* name, int english, int math) {
Student* newNode = (Student*)malloc(sizeof(Student));
strcpy(newNode->name, name);
newNode->english = english;
newNode->math = math;
// 插入尾部
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
}
//增加資料
void add_data(char* name, int english, int math){
Student* newNode = (Student*)malloc(sizeof(Student));
strcpy(newNode->name, name);
newNode->english = english;
newNode->math = math;
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
printf("%s 已增加\n", name);
}
//減少資料
void remove_data(char* name){
prev = head;
current = head->rlink;
while(current!=tail &&strcmp(name,current->name)!=0){
prev=current;
current=current->rlink;
}
if(current != tail){
current->rlink->llink = prev;
prev->rlink = current->rlink;
printf("%s 已刪除\n", name);
free(current);
}else /* 找不到資料則顯示錯誤 */
printf(" %s 不在串列中\n", name);
}
// 從文件讀取學生資料
void readStudentsFromFile(char* filename) {
file = fopen(filename, "r");
if (file == NULL) {
printf("無法開啟檔案 %s\n", filename);
exit(0);
}
char line[100];
int lineCount = 0;
// 跳過前四行
while (lineCount < 4 && fgets(line, sizeof(line), file)) {
lineCount++;
}
// 讀取學生資料
char name[MAX_NAME_LENGTH];
int english, math;
// %[ ]表示要讀入一個字符集合
// %23[^\t]為「讀取最多23個字符直到遇到\t為止」 ^為非 不是\t就讀
while(fgets(line, sizeof(line), file)!=NULL){
if(isalpha(line[0])){
sscanf(line, "%23[^\t]\t%d\t%d\n", name, &english, &math);
insertStudent(name, english, math);
}else if(line[0]=='*'){
break;
}
}
// 此flocse為測試用 正常使用應在modify_list的尾端
// fclose(file);
}
// 執行***後的增加或減少資料
void modify_list(){
char name[MAX_NAME_LENGTH];
int english, math;
char line[100];
while(fgets(line, sizeof(line), file)!=NULL){
if(line[0]=='+'){
sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math);
printf("\n===============================\n");
printf("增加一筆資料\n\n");
add_data(name, english, math);
printStudentList();
}else if(line[0]=='-'){
sscanf(line, "%*[^ ] %[^\t]\t%d\t%d\n", name, &english, &math);
printf("\n===============================\n");
printf("刪除一筆資料\n\n");
remove_data(name);
printStudentList();
}
}
fclose(file);
}
// 列印學生列表
void printStudentList() {
current = head->rlink;
printf("\n從頭開始\n");
printf("\n姓名\t\t英文\t數學\n");
printf("--------------------------------\n");
while (current != tail) {
printf("%-15s\t%d\t%d\n", current->name, current->english, current->math);
current = current->rlink;
}
current = tail->llink;
printf("\n從尾開始\n");
printf("\n姓名\t\t英文\t數學\n");
printf("--------------------------------\n");
while (current != head) {
printf("%-15s\t%d\t%d\n", current->name, current->english, current->math);
current = current->llink;
}
}
//依照mode進行排序
void sort(int mode , int target){
list_length = 0;
//若沒有資料或只有一筆資料
if (head->rlink == tail || head->rlink->rlink == tail) {
return;
}
current = head->rlink;
while(current!=tail){
list_length++;
current = current->rlink;
}
Student **arr = (Student**)malloc(list_length*(sizeof(Student*)));
current = head->rlink;
for(int i = 0; i < list_length; i++) {
arr[i] = current;
current = current->rlink;
}
for(int i = 0; i < list_length-1; i++) {
for(int j = 0; j < list_length-1-i; j++) {
if(mode==0) {
if(strcmp(arr[j]->name, arr[j+1]->name) > 0){
Student *temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}else if(mode==1){
if(arr[j]->english < arr[j+1]->english ){
Student *temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
} else if(mode==2){
if(arr[j]->math < arr[j+1]->math ){
Student *temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
if(target != -1){
if(target != 0 && target<=list_length){
printf("排名第%d的學生為\n\n"
"姓名\t\t英文\t數學\n%-15s\t%d\t%d", target, arr[target-1]->name, arr[target-1]->english, arr[target-1]->math);
printf("\n*****************************\n");
}else if(target == 0 && target >= list_length){
printf("\n*****************************\n");
printf("資料不存在");
printf("\n*****************************\n");
}
}
// 顯示排序後的結果
printf("\n排名\t姓名\t\t英文\t數學\n");
printf("---------------------------------------------\n");
for(int i = 0; i < list_length; i++) {
printf("%d\t%-15s\t%d\t%d\n", i+1, arr[i]->name, arr[i]->english, arr[i]->math);
}
printf("---------------------------------------------\n");
}
//選擇科目及排名
void choose_subject(){
int subject ,number , i=1;
printf("\n輸入選擇的科目\n"
"1 數學 2 英文 ==> ");
subject = getche();
switch(subject){
case '1':
printf("\n輸入排名(輸入完畢請按Enter) ==> ");
scanf("%d",&number);
printf("\n數學");
sort(1,number);
break;
case '2':
printf("\n輸入排名(輸入完畢請按Enter) ==> ");
scanf("%d",&number);
printf("\n英文");
sort(2,number);
break;
default :
printf("輸入錯誤");
break;
}
}
//釋放所有節點
void freeAllNodes() {
current = head->rlink;
while (current != tail) {
temp = current;
current = current->rlink;
free(temp);
}
free(head); // 釋放 head 節點
free(tail); // 釋放 tail 節點
free(arr);
}
int main() {
char mode ,sort_mode , name[15];
int english , math;
init_f();
readStudentsFromFile("YunTechStudents.txt");
printStudentList();
modify_list();
while(1){
printf("\n******* 選擇進行排序或是排名第n名的學生 *******\n"
"*--------------------------------------*\n"
"* 1 進行排序 2 選擇排名第n名的學生 3 結束 *\n"
"* 4 顯示原始串列 5 清除畫面 6 增加一筆資料 *\n"
"* 7 刪除一筆資料 *\n"
"\n請選擇功\能 ==> "); //不打成 功\能 在視窗中會變亂碼
mode = getche();
switch(mode){
case '1':
printf("\n\n選擇排序方式\n"
"*--------------------------------------*\n"
"1 名字 2 英文成績 3 數學成績 \n"
"\n請選擇排序方式 ==> ");
sort_mode = getche();
switch(sort_mode){
case '1':
printf("\n\n以名字進行排序\n");
sort(0 ,-1);
break;
case '2':
printf("\n\n以英文成績進行排序\n");
sort(1 ,-1);
break;
case '3':
printf("\n\n以數學成績進行排序\n");
sort(2 ,-1);
break;
default:
printf("\n輸入錯誤\n");
break;
}
break;
case '2':
choose_subject();
break;
case '3':
printf("\n\n謝謝使用Bye~\n");
freeAllNodes();
return 0;
case '4':
printStudentList();
break;
case '5':
system("cls");
break;
case '6':
printf("\n輸入名字 ==> ");
// scanf("%[^\n]",name);
while(getchar() != '\n'); // 清除緩衝區
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; // 移除換行符
printf("\n輸入英文成績 ==> ");
scanf("%d",&english);
printf("\n輸入數學成績 ==> ");
scanf("%d",&math);
add_data(name,english,math);
printStudentList();
break;
case '7':
printf("\n欲刪除輸入名字 ==> ");
// scanf("%[^\n]",name);
while(getchar() != '\n'); // 清除緩衝區
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; // 移除換行符
remove_data(name);
printStudentList();
break;
default:
printf("\n輸入錯誤\n");
break;
}
}
}

BIN
作業/test/DS4_test.exe Normal file

Binary file not shown.

View File

@ -0,0 +1,18 @@
YunTech EE Department (2024)
======================================
Name English Math
---------------+-------+--------------
Steve Jobs 50 60
Tom Cruise 30 40
Marie Jane 70 80
Barrack Obama 46 77
John Tyler 98 96
U. S. Grant 97 88
Robert Redford 22 33
Bruce Lee 90 90
**************************************
+ Oliver Hardy 90 80
+ Slim Pickens 88 82
- Marie Jane 0 0
+ James Bond 88 82
- Barrack Obama 0 0

View File

@ -0,0 +1,20 @@
YunTech EE Department (2024)
======================================
Name English Math
---------------+-------+--------------
Steve Jobs 50 60
Tom Cruise 30 40
Marie Jane 70 80
Barrack Obama 46 77
John Tyler 98 96
U. S. Grant 97 88
Robert Redford 22 33
Bruce Lee 90 90
**************************************
- Steve Jobs 0 0
+ Oliver Hardy 90 80
+ Slim Pickens 88 82
- Marie Jane 0 0
+ James Bond 88 82
- Barrack Obama 0 0
- James Bond 0 0

View File

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void convert(int n, int b, char **result, int *size) {
// 計算需要的位數
int temp = n;
*size = 0;
while (temp > 0) {
temp /= b;
(*size)++;
}
// 配置記憶體
*result = (char*)malloc((*size + 1) * sizeof(char));
if (*result == NULL) {
printf("記憶體配置失敗!\n");
return;
}
// 進行轉換
int i = *size - 1;
while (n > 0) {
int remainder = n % b;
if (remainder < 10) {
(*result)[i] = remainder + '0';
} else {
(*result)[i] = (remainder - 10) + 'A';
}
n /= b;
i--;
}
(*result)[*size] = '\0'; // 添加字串結尾
}
int main() {
int n, b;
char *result; // 用來存放轉換結果的指標
int size; // 結果的長度
while(1) {
printf("\n輸入待轉換的十進位正整數 ==> ");
scanf("%d", &n);
if(n == -1) break;
printf("\n輸入轉換之基底 ==> ");
scanf("%d", &b);
convert(n, b, &result, &size); // 傳入指標的位址
printf("(%d)_10 = (", n);
for(int i = 0; i < size; i++) {
printf("%c", result[i]);
}
printf(")_%d\n", b);
free(result); // 釋放配置的記憶體
}
printf("程式將結束...按任意鍵繼續\n");
system("pause");
return 0;
}

Binary file not shown.

196
作業/test/ds2_test.cpp Normal file
View File

@ -0,0 +1,196 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct node {
int coef;
int exp;
struct node* rlink;
struct node* llink;
} node;
node *head, *tail, *current, *prev, *temp;
void init_f() {
head = (node *)malloc(sizeof(node));
tail = (node *)malloc(sizeof(node));
head->rlink = tail;
tail->llink = head;
}
void read_poly(char str[] ){
int argCount ;
while (1) {
node* newNode = (node*)malloc(sizeof(node));
argCount = sscanf(str, "%dx^%d%s", &newNode->coef, &newNode->exp, str);
if (argCount >= 2) { // 成功讀取係數和指數
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
if (argCount == 2) {
break ;
}
} else {
if(!isdigit(newNode->coef)){
newNode->exp = 0;
newNode->llink = tail->llink;
newNode->rlink = tail;
tail->llink->rlink = newNode;
tail->llink = newNode;
break ;
}else{
// printf("newNode->coef = %d\n",newNode->coef);
// printf("isdigit(newNode->coef) = %d",isdigit(newNode->coef));
free(newNode);
break ;
}
}
}
}
void clear_node(){
// 釋放記憶體
current = head->rlink;
while (current != tail) {
temp = current;
current = current->rlink;
free(temp);
}
free(head);
free(tail);
}
void show(int p[], int n, int mode){
int i;
if(mode == 0){
printf("\n方程式p(x)= ");
current = head->rlink;
while (current != tail) {
if(abs(current->coef)>1){
printf("%s%d", current->coef > 1? "":"\b",current->coef);
}else if(current->coef == -1){
printf("%s", current->exp == 0? "\b-1":"\b-");
}
switch(current->exp){
case 0:
if(current->coef == 1 ) printf("1+");
else printf("+");
break;
case 1:
printf("x+");
break;
default:
printf("x^%d+",current->exp);
}
current = current->rlink;
}
printf("\b ");
}else { /* mode==1顯示所得解 */
for (i = 0; i < n; i++) printf("%d、",p[i]);
if (n > 0) printf("\b\b ");
}
}
int findRoot(int q[]) /* 找根所得解存入q[],回傳根的個數 */
{
int r, c = 0, i, j, k, sum;
int sign[2] = {1,-1};
current = tail->llink;
r = abs(current->coef); /* 取出最低階項之係數 */
if (current->exp != 0) { /* 最低階項的指數 >= 1則0為可能解 */
if ((i = current->exp) > 0) q[c++] = 0; /* 最低階項的指數設為i */
current = head->rlink;
while(current!=tail){
current->exp -= i; /* 所有項次的指數減去i */
current = current->rlink;
}
}
// r = abs(p[2*p[0]]); /* 取出最低階項之係數 */
for (i = 1; i <= r; i++) { /* 考慮能整除r的因數i須注意正負號 */
if (r%i != 0) continue; /* 不能整除r的i將略過繼續考慮下一個i */
for (j = 0; j < 2; j++) { /* j為0代表考慮+i的情境j為1代表考慮-i的情況 */
for (sum = 0, current = head->rlink ; current!= tail ; current = current->rlink) /* 計算每一項的結果值(係數*x^指數)並累加到sum之中 */
sum += current->coef *(int)(pow(sign[j]*i,current->exp));
if (sum == 0) q[c++] = sign[j]*i; /* bingo! 發現合乎條件的整數根將其寫入q陣列 */
}
}
return c;
}
int main() {
char str[100];
int poly_num , *q ,c , high;
init_f();
printf("\n*** 解多項式之整數根 ***\n\n輸入多項式 ==> ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("輸入錯誤!\n");
return 1;
}
/*
1x^2-100x^0
1x^3-2x^2-1x^1+2x^0
1x^3-7x^2+4x^1+12x^0
1x^4+3x^3-66x^2+52x^1+120x^0
3x^4+9x^3-198x^2+156x^1+360x^0
1x^2-1x^1
2x^ 3 -201 x^2+ 97 x^1 +300
2x^12-195x^11-500x^10
6x^4 - 1x^3 -25x^2 + 4x^1 + 4
1x^5-1x^3-1x^2-1x^1+1x^0
1x^5+1x^3+1x^2+1x^1+1x^0
1x^3+1x^0
*/
read_poly(str);
current = head->rlink;
high= current->exp;
show(q,c,0);
q = (int *)malloc((high + 1) *sizeof(int)); /* p[1]紀錄最高階項之指數,依此值創建足夠元素空間的陣列存放所求得的整數根 */
c = findRoot(q);
if (c > 0) {
printf("\n\n解得整數根為:");
show(q,c,1);
}
else
printf("\n\n整數根不存在\n");
clear_node();
return 0;
}

BIN
作業/test/ds2_test.exe Normal file

Binary file not shown.

74
作業/test/fuzzy_HW1.c Normal file
View File

@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int a , i;
double u1 ,u2 , u1uu2 , u1iu2 , u1b , u2b , u1cu2b , u1bcu2;
// for(i=0;i<11;i++){
// u1=exp(-(pow(i-4,2))/8);
// printf("u1(%d)=%f\n",i,u1);
// }
// printf("\n\n");
// for(i=0;i<11;i++){
// u2=exp(-(pow(i-8,2))/8);
// printf("u2(%d)=%f\n",i,u2);
// }
// for(i=0;i<11;i++){
// u1=exp(-(pow(i-4,2))/8);
// u2=exp(-(pow(i-8,2))/8);
// if(u1>u2){
// printf("u1uu2(%d)=%f\n",i,u1);
// }else{
// printf("u1uu2(%d)=%f\n",i,u2);
// }
// }
// printf("\n\n");
// for(i=0;i<11;i++){
// u1=exp(-(pow(i-4,2))/8);
// u2=exp(-(pow(i-8,2))/8);
// if(u1<u2){
// printf("u1iu2(%d)=%f\n",i,u1);
// }else{
// printf("u1iu2(%d)=%f\n",i,u2);
// }
// }
// printf("\n\n");
// for(i=0;i<11;i++){
// u1b=1-(exp(-(pow(i-4,2))/8));
// printf("u1b(%d)=%f\n",i,u1b);
// }
// printf("\n\n");
// for(i=0;i<11;i++){
// u2b=1-(exp(-(pow(i-8,2))/8));
// printf("u2b(%d)=%f\n",i,u2b);
// }
// printf("\n\n");
//
for(i=0;i<11;i++){
u1=exp(-(pow(i-4,2))/8);
u2b=1-(exp(-(pow(i-8,2))/8));
if(u1<u2b){
printf("u1cu2b(%d)=%f\n",i,u1);
}else{
printf("u1cu2b(%d)=%f\n",i,u2b);
}
}
printf("\n\n");
for(i=0;i<11;i++){
u1b=1-(exp(-(pow(i-4,2))/8));
u2=exp(-(pow(i-8,2))/8);
if(u1b<u2){
printf("u1bcu2(%d)=%f\n",i,u1b);
}else{
printf("u1bcu2(%d)=%f\n",i,u2);
}
}
return 0;
}

BIN
作業/test/fuzzy_HW1.o Normal file

Binary file not shown.

View File

@ -0,0 +1,28 @@
# Project: Project1
# Makefile created by Dev-C++ 5.11
CPP = g++.exe
CC = gcc.exe
WINDRES = windres.exe
OBJ = main.o
LINKOBJ = main.o
LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN = Project1.exe
CXXFLAGS = $(CXXINCS)
CFLAGS = $(INCS)
RM = rm.exe -f
.PHONY: all all-before all-after clean clean-custom
all: all-before $(BIN) all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
$(BIN): $(OBJ)
$(CC) $(LINKOBJ) -o $(BIN) $(LIBS)
main.o: main.c
$(CC) -c main.c -o main.o $(CFLAGS)

View File

@ -0,0 +1,62 @@
[Project]
FileName=Project1.dev
Name=Project1
Type=1
Ver=2
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=0
Icon=
ExeOutput=
ObjectOutput=
LogOutput=
LogOutputEnabled=0
OverrideOutput=0
OverrideOutputName=
HostApplication=
UseCustomMakefile=0
CustomMakefile=
CommandLine=
Folders=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000000000000
UnitCount=1
[VersionInfo]
Major=1
Minor=0
Release=0
Build=0
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
SyncProduct=1
[Unit1]
FileName=main.c
CompileCpp=0
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

Binary file not shown.

View File

@ -0,0 +1,8 @@
[Editors]
Order=0
Focused=0
[Editor_0]
CursorCol=21
CursorRow=9
TopLine=1
LeftChar=1

View File

@ -0,0 +1,68 @@
#include<stdio.h>
#include<stdlib.h>
void mul (int **a,int**b,int **c, int m , int k , int n){
int i , j ,l , sum;
for (i=0;i<m;i++){
for (j=0;j<n;j++){
sum = 0;
for(l=0;l<k;l++){
sum += a[i][l]*b[l][j];
}c[i][j]=sum;
}
}
}
int main(){
int i , j ,m=2 , k=3 , n=4 ;
int a[2][3]={{1,2,7},{3,4,1}};
int b[3][4]={{5,6,2,4},{7,8,2,4},{7,2,6,1}};
int **arr_a = (int**)malloc( m *sizeof(int*));
int **arr_b = (int**)malloc( k *sizeof(int*));
int **arr_c = (int**)malloc( m *sizeof(int*));
for (i=0;i<m;i++){
arr_a[i] = (int*)malloc( k *sizeof(int));
arr_c[i] = (int*)malloc( n *sizeof(int));
}
for (i=0;i<k;i++){
arr_b[i] = (int*)malloc( n *sizeof(int));
}
for(i=0;i<m;i++){
for(j=0;j<k;j++){
arr_a[i][j] = a[i][j];
}
}
for(i=0;i<k;i++){
for(j=0;j<n;j++){
arr_b[i][j] = b[i][j];
}
}
mul (arr_a,arr_b,arr_c,m,k,n);
// printf("%d\n",arr_b[2][2]);
//
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("c[%d][%d]=%d\n",i,j,arr_c[i][j]);
}
}
free(arr_a);
free(arr_b);
free(arr_c);
for (i=0;i<m;i++){
free(arr_a[i]);
free(arr_c[i]);
}
for (i=0;i<k;i++){
free(arr_b[i]);
}
return 0 ;
}

BIN
作業/test/mul_byme/main.o Normal file

Binary file not shown.

13
作業/test/try.cpp Normal file
View File

@ -0,0 +1,13 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
printf("1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*(int)pow(2,-2.5))*cos(123.456) = %g\n",1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*pow(2,-2.5))*cos(123.456));
printf("sin((-50.2+sin(3.8*20) = %g\n",sin((-50.2+sin(3.8*20))));
printf("\n*** 解多項式之整數根 ***\n\n輸入多項式 ==> ");
// 1+sin((-50.2+sin(3.8*20)*cos(-30-100%40))*2^-2.5)*cos(123.456)
return 0;
}

BIN
作業/test/try.exe Normal file

Binary file not shown.

28
作業/unit0/Makefile.win Normal file
View File

@ -0,0 +1,28 @@
# Project: Project1
# Makefile created by Dev-C++ 5.11
CPP = g++.exe -D__DEBUG__
CC = gcc.exe -D__DEBUG__
WINDRES = windres.exe
OBJ = Untitled1.o
LINKOBJ = Untitled1.o
LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc -g3
INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN = unit0_bowling_1.exe
CXXFLAGS = $(CXXINCS) -g3
CFLAGS = $(INCS) -g3
RM = rm.exe -f
.PHONY: all all-before all-after clean clean-custom
all: all-before $(BIN) all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
$(BIN): $(OBJ)
$(CC) $(LINKOBJ) -o $(BIN) $(LIBS)
Untitled1.o: Untitled1.c
$(CC) -c Untitled1.c -o Untitled1.o $(CFLAGS)

55
作業/unit0/Untitled1.c Normal file
View File

@ -0,0 +1,55 @@
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct game {
char name[8]; /* 參賽者姓名 */
int score; /* 得分 */
}GAME;
int main(){
int i=0 ,j=0 ,n ;
GAME temp;
char input[20];
GAME * bowling = (GAME*)malloc(sizeof(GAME));
printf("輸入參賽者資訊\n");
while(1){
printf("第%d位參賽者名字 得分 => ",i+1);
// fgets(input,sizeof(input),stdin);
if(fgets(input,sizeof(input),stdin) == NULL||(strcmp(input,"\n")) == 0 ){
break;
}
bowling = (GAME*)realloc(bowling ,(i+1)* sizeof(GAME));
sscanf(input,"%s%d",bowling[i].name,&bowling[i].score);
i++;
n=i;
}
for(i=0;i<n;i++){
for(j=0;j<n-i-1;j++){
if(bowling[j].score<bowling[j+1].score){
temp = bowling[j+1];
bowling[j+1]=bowling[j];
bowling[j]=temp;
}
}
}
printf("成績排行\n");
printf("==============\n");
for(i=0;i<n;i++){
if(i+1==1) printf("%d. %s\t%d 冠軍\n",i+1,bowling[i].name,bowling[i].score);
else if(i+1==2) printf("%d. %s\t%d 亞軍\n",i+1,bowling[i].name,bowling[i].score);
else if(i+1==3) printf("%d. %s\t%d 季軍\n",i+1,bowling[i].name,bowling[i].score);
else
printf("%d. %s\t%d\n",i+1,bowling[i].name,bowling[i].score);
}
free(bowling);
return 0 ;
}

BIN
作業/unit0/Untitled1.o Normal file

Binary file not shown.

Binary file not shown.

36
作業/unit0/bowling_1.c Normal file
View File

@ -0,0 +1,36 @@
#include <stdio.h>
typedef struct game {
char name[8]; /* 參賽者姓名 */
int score; /* 得分 */
}GAME;
void bubble_sort(GAME arr[], int total) {
int i,j;
for (i = 0; i < total - 1; i++) {
for (j = 0; j < total - i - 1; j++) {
if (arr[j].score < arr[j + 1].score) {
GAME temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main(){
GAME bowling[] = {{"Jack",198},{"Tom",185},{"Bob",210},{"Fred",205},{"Mary",170}};
int total =sizeof (bowling)/sizeof(bowling[0]);
bubble_sort(bowling,total);
int i,j;
printf("成績排行\n");
printf("---------\n");
for(j=0;j<total;j++){
printf("%d. %s\t%d\n",j+1,bowling[j].name,bowling[j].score);
}
return 0;
}

BIN
作業/unit0/bowling_1.exe Normal file

Binary file not shown.

BIN
作業/unit0/bowling_1.o Normal file

Binary file not shown.

67
作業/unit0/bowling_2.c Normal file
View File

@ -0,0 +1,67 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct game {
char name[8]; // 參賽者姓名
int score; // 得分
} GAME;
int main() {
GAME *bowling = NULL;
int total = 0;
int i, j;
char input[32];
printf("請逐筆輸入參賽者的資訊...\n");
while (1) {
printf("輸入第%d位參賽者名字 得分 => ", total + 1);
if (fgets(input, sizeof(input), stdin) == NULL) {
break;
}
if (strcmp(input, "\n") == 0) {
break;
}
GAME *temp = realloc(bowling, (total + 1) * sizeof(GAME));
if (temp == NULL) {
printf("Memory allocation error\n");
free(bowling);
return 1;
}
bowling = temp;
sscanf(input, "%s %d", bowling[total].name, &bowling[total].score);
total++;
}
printf("\n成績排名\n============\n");
// Sorting
for (i = 0; i < total - 1; i++) {
for (j = 0; j < total - i - 1; j++) {
if (bowling[j].score < bowling[j+1].score) {
GAME temp = bowling[j];
bowling[j] = bowling[j+1];
bowling[j+1] = temp;
}
}
}
// Printing results
for (i = 0; i < total; i++) {
if (i == 0)
printf("%d. %s %d 冠軍\n", i + 1, bowling[i].name, bowling[i].score);
else if (i == 1)
printf("%d. %s %d 亞軍\n", i + 1, bowling[i].name, bowling[i].score);
else if (i == 2)
printf("%d. %s %d 季軍\n", i + 1, bowling[i].name, bowling[i].score);
else
printf("%d. %s %d\n", i + 1, bowling[i].name, bowling[i].score);
}
free(bowling);
return 0;
}

BIN
作業/unit0/bowling_2.exe Normal file

Binary file not shown.

BIN
作業/unit0/bowling_2.o Normal file

Binary file not shown.

View File

@ -0,0 +1,114 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Player {
char name[8];
int score;
struct Player* next;
} Player;
Player* createPlayer(const char* name, int score) {
Player* newPlayer = (Player*)malloc(sizeof(Player));
if (newPlayer == NULL) {
fprintf(stderr, "記憶體分配失敗\n");
exit(1);
}
strncpy(newPlayer->name, name, 7);
newPlayer->name[7] = '\0';
newPlayer->score = score;
newPlayer->next = NULL;
return newPlayer;
}
void addPlayer(Player** head, const char* name, int score) {
Player* newPlayer = createPlayer(name, score);
newPlayer->next = *head;
*head = newPlayer;
}
void sortPlayers(Player** head) {
int swapped;
Player* ptr1;
Player* lptr = NULL;
if (*head == NULL)
return;
do {
swapped = 0;
ptr1 = *head;
while (ptr1->next != lptr) {
if (ptr1->score < ptr1->next->score) {
int tempScore = ptr1->score;
char tempName[8];
strcpy(tempName, ptr1->name);
ptr1->score = ptr1->next->score;
strcpy(ptr1->name, ptr1->next->name);
ptr1->next->score = tempScore;
strcpy(ptr1->next->name, tempName);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
void printResults(Player* head) {
printf("\n成績排名\n============\n");
int rank = 1;
while (head != NULL) {
if (rank == 1)
printf("%d. %s %d 冠軍\n", rank, head->name, head->score);
else if (rank == 2)
printf("%d. %s %d 亞軍\n", rank, head->name, head->score);
else if (rank == 3)
printf("%d. %s %d 季軍\n", rank, head->name, head->score);
else
printf("%d. %s %d\n", rank, head->name, head->score);
head = head->next;
rank++;
}
}
void freeList(Player* head) {
Player* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main() {
Player* head = NULL;
char input[32];
char name[8];
int score;
printf("請逐筆輸入參賽者的資訊...\n");
while (1) {
printf("輸入參賽者名字 得分或按Enter結束=> ");
if (fgets(input, sizeof(input), stdin) == NULL || strcmp(input, "\n") == 0) {
break;
}
if (sscanf(input, "%7s %d", name, &score) == 2) {
addPlayer(&head, name, score);
} else {
printf("輸入格式錯誤,請重新輸入。\n");
}
}
sortPlayers(&head);
printResults(head);
freeList(head);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct game {
char name[8]; // 參賽者姓名
int score; // 得分
} GAME;
int main() {
GAME *bowling ; // 動態分配記憶體的指標
int total = 0; // 參賽者數量
int i , j ,temp;
char input[32]; // 暫存用來處理輸入
printf("請逐筆輸入參賽者的資訊...\n");
while (1) {
// 提示輸入參賽者名稱與得分
printf("輸入第%d位參賽者名字 得分 => ", total + 1);
// 讀取一行輸入
fgets(input, sizeof(input), stdin);
// 若按下<Enter>直接結束輸入,結束輸入過程
if (strcmp(input, "\n") == 0) {
break;
}
// 動態分配記憶體空間以保存新的參賽者資料
bowling = (GAME *)malloc( (total + 1) * sizeof(GAME));
// printf("分配的記憶體位址: %p\n", (void *)bowling);
// 解析輸入的名稱和得分
sscanf(input, "%s %d", bowling[total].name, &bowling[total].score);
total++;
}
// 顯示輸入結果
printf("\n成績排名\n============\n");
for (i=0 ; i<total-1;i++){
for(j=0 ; j<total-i-1;j++){
if (bowling[j].score<bowling[j+1].score){
temp = bowling[j+1].score;
bowling[j+1].score = bowling[j].score;
bowling[j].score = temp;
}
}
}
for (i = 0; i < total; i++) {
if(i + 1==1)
printf("%d. %s %d 冠軍\n", i + 1, bowling[i].name, bowling[i].score);
else if(i + 1==2)
printf("%d. %s %d 亞軍\n", i + 1, bowling[i].name, bowling[i].score);
else if(i + 1==3)
printf("%d. %s %d 季軍\n", i + 1, bowling[i].name, bowling[i].score);
else if (i + 1 >3)
printf("%d. %s %d\n", i + 1, bowling[i].name, bowling[i].score);
}
// 釋放動態記憶體
free(bowling);
return 0;
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>
void swap(int *,int *);
int main(){
int x=14,y=62;
int ptr_a = &x,ptr_b = &y;
printf("Initial ...\n");
printf("x=%d , y=%d\n",x,y);
swap (&x,&y);
printf("\nEnd swap ...\n");
printf("x=%d , y=%d\n",x,y);
return 0;
}
void swap(int *a,int *b){
int temp;
printf("\nin swap ...\n");
printf("a=%d , b=%d\n",*a,*b);
temp = *a;
*a=*b;
*b=temp;
printf("\nafter swap ...\n");
printf("a=%d , b=%d\n",*a,*b);
}

BIN
作業/unit0/pointer_func.o Normal file

Binary file not shown.

View File

@ -0,0 +1,62 @@
[Project]
FileName=unit0_bowling_1.dev
Name=Project1
Type=1
Ver=2
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=0
Icon=
ExeOutput=
ObjectOutput=
LogOutput=
LogOutputEnabled=0
OverrideOutput=0
OverrideOutputName=
HostApplication=
UseCustomMakefile=0
CustomMakefile=
CommandLine=
Folders=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000001000000
UnitCount=1
[VersionInfo]
Major=1
Minor=0
Release=0
Build=0
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
SyncProduct=1
[Unit1]
FileName=Untitled1.c
CompileCpp=0
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

Binary file not shown.

View File

@ -0,0 +1,13 @@
[Editors]
Order=0
Focused=0
[Editor_0]
CursorCol=76
CursorRow=23
TopLine=7
LeftChar=1
[Editor_1]
CursorCol=1
CursorRow=1
TopLine=1
LeftChar=1

View File

@ -0,0 +1,28 @@
# Project: Project1
# Makefile created by Dev-C++ 5.11
CPP = g++.exe
CC = gcc.exe
WINDRES = windres.exe
OBJ = test_3.o
LINKOBJ = test_3.o
LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN = Project1.exe
CXXFLAGS = $(CXXINCS)
CFLAGS = $(INCS)
RM = rm.exe -f
.PHONY: all all-before all-after clean clean-custom
all: all-before $(BIN) all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
$(BIN): $(OBJ)
$(CC) $(LINKOBJ) -o $(BIN) $(LIBS)
test_3.o: test_3.cpp
$(CC) -c test_3.cpp -o test_3.o $(CFLAGS)

View File

@ -0,0 +1,52 @@
[Project]
FileName=Project1.dev
Name=Project1
Type=1
Ver=2
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=0
Icon=
ExeOutput=
ObjectOutput=
LogOutput=
LogOutputEnabled=0
OverrideOutput=0
OverrideOutputName=
HostApplication=
UseCustomMakefile=0
CustomMakefile=
CommandLine=
Folders=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000000000000
UnitCount=0
[VersionInfo]
Major=1
Minor=0
Release=0
Build=0
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
SyncProduct=1

View File

@ -0,0 +1,13 @@
[Editor_1]
CursorCol=3
CursorRow=40
TopLine=16
LeftChar=1
[Editor_0]
CursorCol=11
CursorRow=10
TopLine=1
LeftChar=1
[Editors]
Order=
Focused=0

View File

@ -2,8 +2,8 @@
#include <stdlib.h>
#include <math.h>
#define f(x) (x+sin(x)-1)
//#define f(x) ((x)*(x))
//#define f(x) (x+sin(x)-1)
#define f(x) ((x)*(x))
//#define f(x) ((x)*exp(x)*(x)*exp(x))
int main() {
@ -14,9 +14,6 @@ int main() {
printf("­¡¥N\t°Ï¶¡\t\t\t\t¤¤¶¡­È\n");
printf("-------+-------------------------------+-------------\n");
printf("%.10f\n",f(num));
//解為0.510973
if(f(num)==(num+sin(num)-1)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
@ -36,12 +33,11 @@ int main() {
}
}
//解為0
if(f(num)==(num*num)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t¸Ñ=%.10f\n",i+1,lower,upper,mid);
// printf("\nf(mid)=%.10f, f(lower)=%.10f, f(upper)=%.10f\n",f(mid),f(lower),f(upper));
printf("\nf(mid)=%.10f, f(lower)=%.10f, f(upper)=%.10f\n",f(mid),f(lower),f(upper));
if (fabs(f(mid)) < precision) {
break;
@ -58,7 +54,6 @@ int main() {
}
}
//唯一解為0,趨近解所有為小於-5的負數
if(f(num)==((num)*exp(num)*(num)*exp(num))){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;

View File

@ -0,0 +1,79 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#define f(x) (x+sin(x)-1)
//#define f(x) ((x)*(x))
#define f(x) ((x)*exp(x)*(x)*exp(x))
int main() {
int count = 1000 , i=0;
double precision = 1e-10 ;
//num為選擇解哪個方程式
double mid , lower=-20 , upper=100, num=2;
if(f(num)==(num+sin(num)-1)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t解=%.10f\n",i+1,lower,upper,mid);
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) * f(lower) < 0) {
upper = mid;
} else {
lower = mid;
}
}
}
if(f(num)==(num*num)){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
printf("\n#%d\t[%.10f,%.10f]\t解=%.10f\n",i+1,lower,upper,mid);
printf("\nf(mid)=%f, f(lower)=%f, f(upper)=%f\n",f(mid),f(lower),f(upper));
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) > precision) {
if(mid>0){
upper = mid;
} else if(mid<0){
lower = mid;
}
}
}
}
if(f(num)==((num)*exp(num)*(num)*exp(num))){
while (upper - lower > precision && i < count ) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t解=%.10f\n",i+1,lower,upper,mid);
// printf("mid=%.10f,f(mid)=%.10f\n",mid,f(mid));
if (fabs(f(mid)) < precision) {
break;
}
i++;
if ( f(mid) > precision) {
if(mid>0){
upper = mid;
} else if(mid<0){
lower = mid;
}
}
}
}
printf("\n答案為%f",mid);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,34 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define f(x) ((x) + sin(x) - 1)
int main() {
int count = 1000, i = 0;
double precision = 1e-15;
double epsilon = 1e-15;
double mid, lower = 0, upper = 2;
while ((upper - lower > precision) && (i < count)) {
mid = (lower + upper) / 2.0;
double f_mid = f(mid);
printf("#%d\t[%.15f,%.15f]\t¸Ñ=%.15f\tf(mid)=%.15e\n", i+1, lower, upper, mid, f_mid);
if (fabs(f_mid) < epsilon) {
break;
}
i++;
if (f_mid * f(lower) < 0) {
upper = mid;
} else {
lower = mid;
}
}
printf("µª®×¬°%.15f\n", mid);
printf("f(mid) = %.15e\n", f(mid));
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,49 @@
#include <stdio.h>
#include <math.h>
#define EPSILON 1e-6
#define MAX_ITERATIONS 100
double f(double x, double a) {
return x * x - a;
}
double bisection_method(double a, double left, double right) {
double mid;
int iterations = 0;
while (right - left > EPSILON && iterations < MAX_ITERATIONS) {
mid = (left + right) / 2;
if (f(mid, a) == 0.0) {
return mid;
} else if (f(mid, a) * f(left, a) < 0) {
right = mid;
} else {
left = mid;
}
iterations++;
}
return (left + right) / 2;
}
int main() {
double a, result;
printf("請輸入一個正數 a 來求解 x^2 = a: ");
scanf("%lf", &a);
if (a < 0) {
printf("錯誤a 必須是非負數\n");
return 1;
}
result = bisection_method(a, 0, a > 1 ? a : 1);
printf("方程 x^2 = %.6f 的解約為 x = %.6f\n", a, result);
printf("驗證:%.6f^2 = %.6f\n", result, result * result);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,32 @@
#include<stdio.h>
#include<stdlib.h>
#include<>
int main(){
double x,mid ,precision=1e-10;
int i=0, count=1000;
printf("¿é¤Jx­È");
scanf("%lf",&x);
double upper=x,lower=0;
mid=(upper+lower)/2;
while (fabs((mid*mid)-x)> precision && i < count){
mid=(upper+lower)/2;
printf("#%d\t[%f,%f]\t¸Ñ=%f\n",i+1,lower,upper,mid);
i++;
if(fabs(mid-x) <precision){
break;
}else if(mid*mid>x){
upper=mid;
// lower=mid;
}else{
// upper=mid;
lower=mid;
}
}
printf("%f",mid);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,44 @@
#include <iostream>
#include <iomanip>
#include <cmath>
#define f(x) ((x) * (x) - a) // 定義方程式 f(x)
using namespace std;
int main() {
double a;
cout << "平方根的數值 a= ";
cin >> a;
cout << "----------------------------------------"<< endl;
double c=sqrt(a);
double left = 0, right = 20; // 設定範圍
double b = 1e-10;
double mid;
int i = 0;
while ((right - left) > b) {
mid = (left + right) / 2.0;
i++;
printf("#%d [%f %f ]\n", i, left, right);
if (f(mid) == 0.0) {
cout << "根的近似值為: " << mid << " 且 f(x)= " << f(mid) << endl;
return 0;
}
if (f(left) * f(mid) < 0) {
right = mid; // 左邊
} else {
left = mid; // 右邊
}
}
cout << "-----------------------------------------"<< endl;
int d=((mid - c) / (c)) * 100 ;
if(d>0)
d=d;
else
d=-d;
cout << "sqrt("<< a <<"): " << sqrt(a) << " 誤差值為(%)" << d << endl;
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,28 @@
# Project: Project1
# Makefile created by Dev-C++ 5.11
CPP = g++.exe
CC = gcc.exe
WINDRES = windres.exe
OBJ = binary-search-square-root.o
LINKOBJ = binary-search-square-root.o
LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN = Project1.exe
CXXFLAGS = $(CXXINCS)
CFLAGS = $(INCS)
RM = rm.exe -f
.PHONY: all all-before all-after clean clean-custom
all: all-before $(BIN) all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
$(BIN): $(OBJ)
$(CC) $(LINKOBJ) -o $(BIN) $(LIBS)
binary-search-square-root.o: binary-search-square-root.c
$(CC) -c binary-search-square-root.c -o binary-search-square-root.o $(CFLAGS)

View File

@ -0,0 +1,62 @@
[Project]
FileName=Project1.dev
Name=Project1
Type=1
Ver=2
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=0
Icon=
ExeOutput=
ObjectOutput=
LogOutput=
LogOutputEnabled=0
OverrideOutput=0
OverrideOutputName=
HostApplication=
UseCustomMakefile=0
CustomMakefile=
CommandLine=
Folders=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000000000000
UnitCount=1
[VersionInfo]
Major=1
Minor=0
Release=0
Build=0
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
SyncProduct=1
[Unit1]
FileName=E:\¬ö¦Ñ®v±Ð§÷\§@·~\unit1\binary-search-square-root.c
CompileCpp=0
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

View File

@ -0,0 +1,8 @@
[Editor_0]
CursorCol=2
CursorRow=18
TopLine=1
LeftChar=1
[Editors]
Order=0
Focused=0

View File

@ -34,7 +34,7 @@ int main() {
}
if(x<1){
lower=0 , upper=1 ,i=0;
lower=x , upper=1 ,i=0;
printf("\n使用二元搜尋法求解過程如下...\n");
printf("\n迭代\t區間\t\t\t\t中間值\n");
printf("-------+-------------------------------+-------------\n");

View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i;
double precision = 1e-10 , x;
printf("***輸入x值(x>0)計算平方根***\n");
printf("輸入x值=> ");
scanf("%lf",&x);
double mid , lower , upper;
if(x<0){
printf("錯誤! X值不能<1");
return 1;
}
if(x>1){
lower=0 , upper=x , i=0;
while (upper - lower > precision) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t解=%.10f\n",i+1,lower,upper,mid);
i++;
if (mid * mid > x) {
upper = mid;
} else {
lower = mid;
}
}
}
if(x<1){
lower=x , upper=1 ,i=0;
while (upper - lower > precision) {
mid = (lower + upper) / 2.0;
printf("#%d\t[%.10f,%.10f]\t解=%.10f\n",i+1,lower,upper,mid);
i++;
if (mid * mid > x) {
upper = mid;
} else {
lower = mid;
}
}
}
printf("%f的平方根為%.10f\n",x,mid);
printf("sqrt(%f)的結果為%.10f\n",x,sqrt(x));
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int x;
double precision = 1e-5;
printf("***輸入x值(x>0)計算平方根***\n");
// 清空輸入緩衝區
int c;
while ((c = getchar()) != '\n' && c != EOF);
// 使用 fgets 和 sscanf 來讀取輸入
char input[100];
if (fgets(input, sizeof(input), stdin) == NULL) {
printf("讀取輸入時發生錯誤\n");
return 1;
}
if (sscanf(input, "%d", &x) != 1 || x <= 0) {
printf("無效的輸入。請輸入一個正整數。\n");
return 1;
}
int lower = 0, upper = x;
double ans = sqrt(x);
double mid;
while (upper - lower > precision) {
mid = (lower + upper) / 2.0;
if (mid * mid > x) {
upper = mid;
} else {
lower = mid;
}
}
printf("%d的平方根為%f\n", x, mid);
printf("sqrt(%d)的結果為%f\n", x, ans);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,28 @@
# Project: Project3
# Makefile created by Dev-C++ 5.11
CPP = g++.exe
CC = gcc.exe
WINDRES = windres.exe
OBJ = test3.o
LINKOBJ = test3.o
LIBS = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN = Project3.exe
CXXFLAGS = $(CXXINCS)
CFLAGS = $(INCS)
RM = rm.exe -f
.PHONY: all all-before all-after clean clean-custom
all: all-before $(BIN) all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
$(BIN): $(OBJ)
$(CC) $(LINKOBJ) -o $(BIN) $(LIBS)
test3.o: test3.c
$(CC) -c test3.c -o test3.o $(CFLAGS)

View File

@ -0,0 +1,62 @@
[Project]
FileName=Project3.dev
Name=Project3
Type=1
Ver=2
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=0
Icon=
ExeOutput=
ObjectOutput=
LogOutput=
LogOutputEnabled=0
OverrideOutput=0
OverrideOutputName=
HostApplication=
UseCustomMakefile=0
CustomMakefile=
CommandLine=
Folders=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000000000000
UnitCount=1
[VersionInfo]
Major=1
Minor=0
Release=0
Build=0
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
SyncProduct=1
[Unit1]
FileName=E:\¬ö¦Ñ®v±Ð§÷\§@·~\matrix-multiplication\matrix-multiplication.c
CompileCpp=0
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

View File

@ -0,0 +1,18 @@
[Editor_1]
CursorCol=17
CursorRow=3
TopLine=1
LeftChar=1
[Editors]
Order=0
Focused=0
[Editor_0]
CursorCol=16
CursorRow=74
TopLine=64
LeftChar=1
[Editor_2]
CursorCol=26
CursorRow=41
TopLine=1
LeftChar=1

View File

@ -0,0 +1,69 @@
#include<stdio.h>
#include<stdlib.h>
void mul(int **a ,int **b,int **c ,int m , int k ,int n){
int i , j , l ,sum;
for (i=0;i<m;i++){
for(j=0;j<n;j++){
sum = 0;
for(l=0;l<k;l++){
sum += a[i][l]*b[l][j];
}c[i][j]=sum;
}
}
}
int main(){
int i , j ,m=2,k=3,n=4;
int a[2][3]={{1,2,7},{3,4,1}};
int b[3][4]={{5,6,2,4},{7,8,2,4},{7,2,6,1}};
int **arr_a = (int**)malloc(m * sizeof(int*));
int **arr_b = (int**)malloc(k * sizeof(int*));
int **arr_c = (int**)malloc(m * sizeof(int*));
for(i=0;i<m;i++){
arr_a[i] = (int*)malloc(k*sizeof(int));
arr_c[i] = (int*)malloc(n*sizeof(int));
}
for(i=0;i<k;i++){
arr_b[i] = (int*)malloc(n*sizeof(int));
}
for (i=0;i<m;i++){
for(j=0;j<k;j++){
arr_a[i][j]=a[i][j];
}
}
for (i=0;i<k;i++){
for(j=0;j<n;j++){
arr_b[i][j]=b[i][j];
}
}
mul(arr_a,arr_b,arr_c,m,k,n);
for (i=0;i<m;i++){
for(j=0;j<n;j++){
printf("c[%d][%d]=%d\n",i,j,arr_c[i][j]);
}
}
free (arr_a);
free (arr_b);
free (arr_c);
for(i=0;i<m;i++){
free (arr_a[i]);
free (arr_c[i]);
}
for(i=0;i<k;i++){
free (arr_b[i]);
}
return 0 ;
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,128 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1000
// 分配矩陣記憶體
int** allocateMatrix(int rows, int cols) {
int i;
int** matrix = (int**)malloc(rows * sizeof(int*));
for (i = 0; i < rows; i++) {
matrix[i] = (int*)malloc(cols * sizeof(int));
}
return matrix;
}
// 釋放矩陣記憶體
void freeMatrix(int** matrix, int rows) {
int i ;
for (i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
}
// 矩陣乘法
void mul(int **a, int **b, int **c, int m, int k, int n) {
int i , j , l ;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = 0;
for (l = 0; l < k; l++) {
c[i][j] += a[i][l] * b[l][j];
}
}
}
}
// 讀取矩陣並返回維度
int** readMatrix(FILE* file, int* rows, int* cols) {
char line[MAX_LINE_LENGTH];
int** matrix = NULL;
*rows = 0;
*cols = 0;
while (fgets(line, sizeof(line), file)) {
if (strlen(line) <= 1) break; // 空行表示矩陣結束
(*rows)++;
int tempCols = 0;
char* token = strtok(line, " \t\n");
while (token != NULL) {
tempCols++;
token = strtok(NULL, " \t\n");
}
if (*cols == 0) {
*cols = tempCols;
matrix = allocateMatrix(*rows, *cols);
}
if (tempCols != *cols) {
printf("錯誤:矩陣列數不一致\n");
exit(1);
}
// 重新讀取該行並存儲數據
int col = 0;
token = strtok(line, " \t\n");
while (token != NULL) {
matrix[*rows - 1][col++] = atoi(token);
token = strtok(NULL, " \t\n");
}
}
return matrix;
}
int main() {
int i , j ;
FILE *file = fopen("matrix_input.txt", "r");
if (file == NULL) {
printf("無法開啟檔案\n");
return 1;
}
int m, k1, k2, n;
int **arr_a, **arr_b, **arr_c;
// 讀取第一個矩陣
arr_a = readMatrix(file, &m, &k1);
// 讀取第二個矩陣
arr_b = readMatrix(file, &k2, &n);
fclose(file);
// 檢查矩陣是否可以相乘
if (k1 != k2) {
printf("錯誤:這兩個矩陣無法相乘\n");
freeMatrix(arr_a, m);
freeMatrix(arr_b, k2);
return 1;
}
// 分配結果矩陣的空間
arr_c = allocateMatrix(m, n);
// 執行矩陣乘法
mul(arr_a, arr_b, arr_c, m, k1, n);
// 輸出結果
printf("矩陣乘法結果:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", arr_c[i][j]);
}
printf("\n");
}
// 釋放記憶體
freeMatrix(arr_a, m);
freeMatrix(arr_b, k1);
freeMatrix(arr_c, m);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,72 @@
#include <stdio.h>
#include <stdlib.h>
void mul(int **a, int **b, int **c, int n) {
int i, j, k, sum;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
sum = 0;
for (k = 0; k < n; k++) {
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
}
int main() {
int i, j, n = 2;
int ary_a[2][2]={{1,2},{3,4}};
int ary_b[2][2]={{5,6},{7,8}};
// 動態分配記憶體給矩陣
int **arr_a = (int **)malloc(n * sizeof(int *));
int **arr_b = (int **)malloc(n * sizeof(int *));
int **arr_c = (int **)malloc(n * sizeof(int *));
if (arr_a == NULL || arr_b == NULL || arr_c == NULL) {
printf("記憶體分配失敗\n");
return 1;
}
for (i = 0; i < n; i++) {
arr_a[i] = (int *)malloc(n * sizeof(int));
arr_b[i] = (int *)malloc(n * sizeof(int));
arr_c[i] = (int *)malloc(n * sizeof(int));
if (arr_a[i] == NULL || arr_b[i] == NULL || arr_c[i] == NULL) {
printf("記憶體分配失敗\n");
return 1;
}
}
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
arr_a[i][j] = ary_a[i][j];
arr_b[i][j] = ary_b[i][j];
}
}
// 進行矩陣乘法
mul(arr_a, arr_b, arr_c, n);
// 輸出結果
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("arr_c[%d][%d] = %d\n", i, j, arr_c[i][j]);
}
}
// 釋放記憶體
for (i = 0; i < n; i++) {
free(arr_a[i]);
free(arr_b[i]);
free(arr_c[i]);
}
free(arr_a);
free(arr_b);
free(arr_c);
return 0;
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,5 @@
1 2 3 4
5 6 7 8
5 6 7 5
9 10 11 12
-1 -2 -3

View File

@ -0,0 +1,21 @@
#include<stdio.h>
#include<stdlib.h>
#include<string>
define colMAX 100
define rowMAX 100
int main(){
int i , j ;
FILE *file;
char line;
if((file = fopen("matrix_input.txt","r"))==NULL){
return 1 ;
}
fget(line,sizeof(line),file);
return 0;
}

View File

@ -0,0 +1,160 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void mul(int **a, int **b, int **c, int m, int k, int n) {
int i , j , l ;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = 0;
for (l = 0; l < k; l++) {
c[i][j] += a[i][l] * b[l][j];
}
}
}
}
void read_matrix(FILE *file,int *m,int *k,int *n){
char line[1000];
// int *m = 0, *k1 = 0, *k2 = 0, *n = 0;
int *k1 , *k2;
int i, j, temp;
char *token;
while (fgets(line, sizeof(line), file)) {
if (strlen(line) <= 1) {
break;
}
j = 0;
token = strtok(line, " \n");
while (token != NULL) {
j++;
token = strtok(NULL, " \n");
}
if (*k1 == 0) *k1 = j;
m++;
}
// 讀取第二個矩陣
while (fgets(line, sizeof(line), file)) {
j = 0;
token = strtok(line, " \n");
while (token != NULL) {
j++;
token = strtok(NULL, " \n");
}
if (*n == 0) *n = j;
k2++;
*k2 = k2;
}
printf("OK");
// if (*k1!=*k2) return 1;
// if (*k1==*k2){
}
int main() {
FILE *file ;
int *m , *k , *n ;
int i, j, temp;
char *token;
if ((file = fopen("matrix_input.txt", "r")) == NULL){
printf("無法打開文件\n");
return 1;
}
// 讀取第一個矩陣
// while (fgets(line, sizeof(line), file)) {
// if (strlen(line) <= 1) {
// break;
// }
// j = 0;
// token = strtok(line, " \n");
// while (token != NULL) {
// j++;
// token = strtok(NULL, " \n");
// }
// if (k1 == 0) k1 = j;
//
// m++;
// }
//
// // 讀取第二個矩陣
// while (fgets(line, sizeof(line), file)) {
// j = 0;
// token = strtok(line, " \n");
// while (token != NULL) {
// j++;
// token = strtok(NULL, " \n");
// }
// if (n == 0) n = j;
// k2++;
// }
read_matrix(file,&m,&k,&n);
printf("第一個矩陣: %d 行 %d 列\n", *m, *k);
printf("第二個矩陣: %d 行 %d 列\n", *k, *n);
printf("m = %d, k1 = %d, k2 = %d, n = %d\n\n", *m, *k , *k , *n);
//根據m,k,n配置記憶體空間
int **arr_a = (int**)malloc(m * sizeof(int*));
int **arr_b = (int**)malloc(k * sizeof(int*));
int **arr_c = (int**)malloc(m * sizeof(int*));
for(i=0;i<m;i++){
arr_a[i] = (int*)malloc(k*sizeof(int));
arr_c[i] = (int*)malloc(n*sizeof(int));
}
for(i=0;i<k;i++){
arr_b[i] = (int*)malloc(n*sizeof(int));
}
// for (i = 0; i < m; i++) {
// for (j = 0; j < k1; j++) {
// arr_a[i][j] = matrix1[i][j];
// }
// }
//
// for (i = 0; i < k2; i++) {
// for (j = 0; j < n; j++) {
// arr_b[i][j] = matrix2[i][j];
// }
// }
mul(arr_a,arr_b,arr_c,m,k,n);
// printf("%d\n",arr_a[0][1]);
// printf("%d\n",arr_b[0][1]);
// printf("%d\n",arr_c[0][1]);
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("c[%d][%d]=%d\n",i,j,arr_c[i][j]);
}
}
fclose(file);
free (arr_a);
free (arr_b);
free (arr_c);
for(i=0;i<m;i++){
free (arr_a[i]);
free (arr_c[i]);
}
for(i=0;i<k;i++){
free (arr_b[i]);
}
// if(k1!=k2){
// printf("錯誤! 矩陣無法相乘\n");
// fclose(file);
// return 1;
// }
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,128 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1000
// 分配矩陣記憶體
int** allocateMatrix(int rows, int cols) {
int i;
int** matrix = (int**)malloc(rows * sizeof(int*));
for (i = 0; i < rows; i++) {
matrix[i] = (int*)malloc(cols * sizeof(int));
}
return matrix;
}
// 釋放矩陣記憶體
void freeMatrix(int** matrix, int rows) {
int i ;
for (i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
}
// 矩陣乘法
void mul(int **a, int **b, int **c, int m, int k, int n) {
int i , j , l ;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = 0;
for (l = 0; l < k; l++) {
c[i][j] += a[i][l] * b[l][j];
}
}
}
}
// 讀取矩陣並返回維度
int** readMatrix(FILE* file, int* rows, int* cols) {
char line[MAX_LINE_LENGTH];
int** matrix = NULL;
*rows = 0;
*cols = 0;
while (fgets(line, sizeof(line), file)) {
if (strlen(line) <= 1) break; // 空行表示矩陣結束
(*rows)++;
int tempCols = 0;
char* token = strtok(line, " \t\n");
while (token != NULL) {
tempCols++;
token = strtok(NULL, " \t\n");
}
if (*cols == 0) {
*cols = tempCols;
matrix = allocateMatrix(*rows, *cols);
}
if (tempCols != *cols) {
printf("錯誤:矩陣列數不一致\n");
exit(1);
}
// 重新讀取該行並存儲數據
int col = 0;
token = strtok(line, " \t\n");
while (token != NULL) {
matrix[*rows - 1][col++] = atoi(token);
token = strtok(NULL, " \t\n");
}
}
return matrix;
}
int main() {
int i , j ;
FILE *file = fopen("matrix_input.txt", "r");
if (file == NULL) {
printf("無法開啟檔案\n");
return 1;
}
int m, k1, k2, n;
int **arr_a, **arr_b, **arr_c;
// 讀取第一個矩陣
arr_a = readMatrix(file, &m, &k1);
// 讀取第二個矩陣
arr_b = readMatrix(file, &k2, &n);
fclose(file);
// 檢查矩陣是否可以相乘
if (k1 != k2) {
printf("錯誤:這兩個矩陣無法相乘\n");
freeMatrix(arr_a, m);
freeMatrix(arr_b, k2);
return 1;
}
// 分配結果矩陣的空間
arr_c = allocateMatrix(m, n);
// 執行矩陣乘法
mul(arr_a, arr_b, arr_c, m, k1, n);
// 輸出結果
printf("矩陣乘法結果:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", arr_c[i][j]);
}
printf("\n");
}
// 釋放記憶體
freeMatrix(arr_a, m);
freeMatrix(arr_b, k1);
freeMatrix(arr_c, m);
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,109 @@
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 10 /* 定義矩陣的最大大小 */
/* 函數:讀取矩陣 */
int readMatrix(int matrix[MAX_SIZE][MAX_SIZE], int *cols, FILE *file) {
int i = 0, j = 0, temp;
char ch;
while (fscanf(file, "%d", &temp) == 1) {
matrix[i][j] = temp;
j++;
/* 檢查當前行是否結束 */
ch = fgetc(file);
if (ch == '\n') {
if (i == 0) {
*cols = j; // 紀錄第一行的列數
}
i++; /* 移到下一行 */
j = 0; /* 重置列計數 */
}
if (ch == EOF) break;
}
return i; /* 返回行數 */
}
/* 函數:跳過空行 */
void skipEmptyLines(FILE *file) {
char ch;
while ((ch = fgetc(file)) != EOF) {
if (!isspace(ch) || ch == '\n') {
ungetc(ch, file); // 將非空白字符退回流,準備下一次讀取
break;
}
}
}
/* 函數:印出矩陣 */
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
/* 函數:矩陣乘法 */
void multiplyMatrix(int a[MAX_SIZE][MAX_SIZE], int b[MAX_SIZE][MAX_SIZE], int c[MAX_SIZE][MAX_SIZE],
int rowsA, int colsA, int colsB) {
int i, j, k;
for (i = 0; i < rowsA; i++) {
for (j = 0; j < colsB; j++) {
c[i][j] = 0;
for (k = 0; k < colsA; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main() {
FILE *file;
int matrixA[MAX_SIZE][MAX_SIZE] = {0}, matrixB[MAX_SIZE][MAX_SIZE] = {0}, result[MAX_SIZE][MAX_SIZE] = {0};
int rowsA = 0, colsA = 0, rowsB = 0, colsB = 0;
/* 開啟檔案 */
file = fopen("matrix_input.txt", "r");
if (file == NULL) {
printf("無法開啟檔案\n");
return 1;
}
/* 讀取矩陣 A */
rowsA = readMatrix(matrixA, &colsA, file);
/* 跳過空行 */
skipEmptyLines(file);
/* 讀取矩陣 B */
rowsB = readMatrix(matrixB, &colsB, file);
/* 關閉檔案 */
fclose(file);
/* 印出矩陣大小 */
printf("矩陣 A: %d x %d\n", rowsA, colsA);
printf("矩陣 B: %d x %d\n", rowsB, colsB);
/* 檢查矩陣是否可以相乘 */
if (colsA != rowsB) {
printf("錯誤:這兩個矩陣無法相乘\n");
return 1;
}
/* 執行矩陣乘法 */
multiplyMatrix(matrixA, matrixB, result, rowsA, colsA, colsB);
/* 印出結果 */
printf("矩陣乘法結果:\n");
printMatrix(result, rowsA, colsB);
return 0;
}

Binary file not shown.

View File

@ -111,8 +111,8 @@ int main() {
read_matrix(file, arr_b, k, n);
mul(arr_a, arr_b, arr_c, m, k, n);
printf("矩陣相乘結果:\n");
printf("結果矩陣\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", arr_c[i][j]);
@ -132,6 +132,6 @@ int main() {
for (i = 0; i < k; i++) {
free(arr_b[i]);
}
system("pause");
return 0;
}

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More