行列式计算器C语言代码
C语言计算器源代码
C语言计算器源代码以下是一个简单的C语言计算器源代码,可以实现基本的四则运算。
```c#include <stdio.h>int maichar operator;double num1, num2;double result;printf("欢迎使用简单计算器!\n");printf("请输入运算符(+, -, *, /): ");scanf("%c", &operator);printf("请输入第一个数字: ");scanf("%lf", &num1);printf("请输入第二个数字: ");scanf("%lf", &num2);switch (operator)case '+':result = num1 + num2;printf("结果: %.2lf\n", result);break;case '-':result = num1 - num2;printf("结果: %.2lf\n", result); break;case '*':result = num1 * num2;printf("结果: %.2lf\n", result); break;case '/':if (num2 != 0)result = num1 / num2;printf("结果: %.2lf\n", result); } elseprintf("除数不能为0\n");}break;default:printf("无效的运算符\n");}return 0;```运行代码后,程序会首先打印欢迎信息,并要求用户输入运算符、第一个数字和第二个数字。
探讨用C语言实现求解行列式
探讨用C语言实现求解行列式作者:屈晓来源:《电脑知识与技术》2011年第28期摘要:行列式在线性代数中是基础内容,在对行列式进行求解时,由于数值计算量比较大而且使用的方法量有一定的局限性,所以在对行列式求解时,数值的计算量比方法的寻找会更让人关注。
所以该文提出了利用计算机来实现行列式的求解。
利用计算机的计算速度优势,可以对大量数据的行列式进行快速计算。
该文研究的是用C语言实现行列式的降阶法求行列式的值。
关键词:C语言;行列式;降阶法;程序中图分类号:TP271 文献标识码:A文章编号:1009-3044(2011)28-6907-02行列式在线性代数中是基础的内容,但由于其中的数值数据运算量大,特别是高阶行列式,显得比较复杂。
并且在教学中只是挑选一些简单的例子进行说明、解释,作业也比较少,学生也没有足够的时间去深入学习,致使学生对行列式的求解不够充分。
虽然现在计算机已经普及,但线性代数的教学并没有与算法语言的教学联系起来,并没有用计算机来解决线性代数中的教学问题。
对于行列式的计算而言,很多学生只是掌握其中的一种或几种方法来解决行列式的计算,这就花费了大量的时间在数值计算上,并不在方法上。
如果能用计算机来解决计算,就可以大大的节约计算的时间。
该文对行列式的求解,利用C语言进行了一些算法上的探讨,采用递归调用方式对行列式进行第一列展开进行求解,从而能快速、通用的求出行列式的值。
1 行列式简述令(1)叫做n阶行列式。
其中:1)Dn为一个数值,其值为n!项的代数和;2)每一项由Dn中不同行不同列的n个元素乘积组成;3)各项的符号由n级排列a1j1a2j2…anjn的奇偶性确定。
一般来说,行列式的阶数越低越易计算,因此很自然的考虑到能否把一个高阶行列式化为低阶行列式来计算。
所以在此用余子式和代数余子式来解决行列式的计算,利用代数余子式来对行列式按第一列进行展开,并结合行列式的性质,就可以简化行列式的计算。
矩阵计算C语言源代码
//#include "matrix.h"#define EX_TRUE (0)#define EX_FALSE (1)#define EX_MALLOC (2)typedefstruct tagMatrix{unsignedchar ucRow;unsignedchar ucCol;unsignedshort usRev;float *pfDataAdd;}Matrix_s;externint InputRowColInfo(unsignedchar *pucRow, unsignedchar *pucCol); externint CreateMatrixMem(void *pvData);externint InputMatrixData(void *pvData);externint PrintMatrixData(void *pvData);externint PrintInverseMatrixData(void *pvData);externint Show_matrix(Matrix_s *pstMatrixA, Matrix_s *pstMatrixB);//#include "operate_matrix.h"#define EX_MA TRIX_INIT (1)#define EX_MA TRIX_UNINIT (0)typedefenum{EX_INPUT_MATRIX = 1,EX_ADD_MA TRIX,EX_SUBTRACT_MATRIX,EX_MULTIPL Y_MA TRIX,EX_INVERSE_MA TRIX,EX_QUIT_MATRIX,EX_BOTTOM_MATRIX}Matrix_opcode_en;externint OperateMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrix);externint ShowMatrixMenu();externint CheckMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB);externint AddMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC);externint SubtractMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC);externint MultiplyMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC);externint CreateResultMatrix(unsignedchar ucRow, unsignedchar ucCol, void *pvData); externint InverseMatrix(float a[], int n);/*Guanlin Luo ID:10529749*/#include<stdio.h>#include<stdlib.h>#include<memory.h>#include<math.h>#include"matrix.h"/*We have already done this header.*/#include"operate_matrix.h"/*We have already done this header.*/char g_cFlag = EX_MATRIX_UNINIT;int main (){int iInputOpCode;int iRet = EX_FALSE;Matrix_s stMatrixA, stMatrixB;memset(&stMatrixA, 0, sizeof(stMatrixA));memset(&stMatrixB, 0, sizeof(stMatrixB));while(1){/* show menu */(void)ShowMatrixMenu();/* operete matrix */scanf("%d", &iInputOpCode);iRet = OperateMatrix(iInputOpCode, &stMatrixA, &stMatrixB);if (EX_TRUE == iRet){if (EX_QUIT_MATRIX == iInputOpCode){break;}}}if (NULL != stMatrixA.pfDataAdd){free(stMatrixA.pfDataAdd);}if (NULL != stMatrixB.pfDataAdd){free(stMatrixB.pfDataAdd);}return EX_TRUE;}int ShowMatrixMenu()/*choices for users.*/{printf("1 - Enter matrices A & B\r\n");printf("2 - Add matrices\r\n");printf("3 - Subtract matrices\r\n");printf("4 - Multiply matrices\r\n");printf("5 - Inverse of A\r\n");printf("6 - Quit program\r\n");printf("Option: ");return EX_TRUE;}int OperateMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB) {int iRet = EX_FALSE;Matrix_s stMatrixC;float *pfTmpBuf = NULL;memset(&stMatrixC, 0, sizeof(Matrix_s));switch (iOpCode){case EX_INPUT_MA TRIX:iRet = Show_matrix(pstMatrixA, pstMatrixB);if (EX_FALSE == iRet){printf("err input matrix info!\n");return iRet;}else{/* at first, we need input matrix data */g_cFlag = EX_MA TRIX_INIT;}break;case EX_ADD_MATRIX:/*Addition part.*/iRet = AddMatrix(EX_ADD_MATRIX, pstMatrixA, pstMatrixB, &stMatrixC);if (EX_TRUE != iRet)/*For checking.*/{printf("err multiply matrix operation!\n");if (EX_MALLOC == iRet){;}else{free(stMatrixC.pfDataAdd);}return iRet;}printf("\r\nA + B =: \r\n");iRet = PrintMatrixData(&stMatrixC);if (iRet == EX_FALSE){printf("err print Matrix result!\r\n");free(stMatrixC.pfDataAdd);return iRet;}free(stMatrixC.pfDataAdd);break;case EX_SUBTRACT_MA TRIX:/*Subtract two matrices*/iRet = SubtractMatrix(EX_SUBTRACT_MATRIX, pstMatrixA, pstMatrixB, &stMatrixC);if (EX_TRUE != iRet)/*For checking.*/{printf("err subtract matrix operation!\r\n");if (EX_MALLOC == iRet){;}else{free(stMatrixC.pfDataAdd);}return iRet;}printf("\r\nA - B =: \r\n");iRet = PrintMatrixData(&stMatrixC);if (iRet == EX_FALSE){printf("err print Matrix result!\r\n");free(stMatrixC.pfDataAdd);return iRet;}free(stMatrixC.pfDataAdd);break;case EX_MULTIPL Y_MATRIX:/*multiplication part.*/iRet = MultiplyMatrix(EX_MULTIPL Y_MATRIX, pstMatrixA, pstMatrixB, &stMatrixC);if (EX_TRUE != iRet)/*For checking.*/{printf("\r\nerr multiply matrix operation!\r\n");if (EX_MALLOC == iRet){;}else{free(stMatrixC.pfDataAdd);}return iRet;}printf("\r\nA * B =: \r\n");iRet = PrintMatrixData(&stMatrixC);if (EX_TRUE != iRet){printf("err print Matrix result!\r\n");free(stMatrixC.pfDataAdd);return iRet;}free(stMatrixC.pfDataAdd);break;case EX_INVERSE_MATRIX:/*inverse.*/if (EX_MATRIX_UNINIT == g_cFlag)/*For checking the input.*/{printf("please choose 1 operation at first.\r\n");return EX_FALSE;}pfTmpBuf = (float*)malloc(pstMatrixA->ucRow * pstMatrixA->ucCol * sizeof(float));if (pfTmpBuf == NULL)/*For checking.*/{printf("err malloc memory.\r\n");return EX_MALLOC;}else{memset(pfTmpBuf, 0, (pstMatrixA->ucRow * pstMatrixA->ucCol * sizeof(float)));memcpy(pfTmpBuf, pstMatrixA->pfDataAdd, (pstMatrixA->ucRow * pstMatrixA->ucCol * sizeof(float)));}stMatrixC.ucCol = pstMatrixA->ucCol;stMatrixC.ucRow = pstMatrixA->ucRow;stMatrixC.pfDataAdd = pfTmpBuf;iRet = InverseMatrix(stMatrixC.pfDataAdd, stMatrixC.ucRow);if (EX_TRUE != iRet)/*For checking.*/{printf("\r\nerr inverse matrix operation!\r\n");if (EX_MALLOC == iRet){;}else{free(stMatrixC.pfDataAdd);}return iRet;}printf("\r\nInverse of A =: \r\n");iRet = PrintInverseMatrixData(&stMatrixC);if (EX_TRUE != iRet)/*For checking.*/{printf("err print Matrix result!\r\n");free(stMatrixC.pfDataAdd);return iRet;}free(stMatrixC.pfDataAdd);break;case EX_QUIT_MA TRIX:/*users chose to end this program.*/printf("will quit matrix menu!\r\n");break;default:/*For checking.*/printf("err operate code!\r\n");return EX_FALSE;}return EX_TRUE;}int CheckMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB) {if ((pstMatrixA == NULL) || (pstMatrixB == NULL)){printf("matrix para is null.\r\n");return EX_FALSE;}if (EX_MATRIX_UNINIT == g_cFlag){printf("please choose 1 operation at first.\r\n");return EX_FALSE;}switch (iOpCode){case EX_ADD_MATRIX:case EX_SUBTRACT_MA TRIX:if ((pstMatrixA->ucCol == pstMatrixB->ucCol)&& (pstMatrixA->ucRow == pstMatrixB->ucRow)) {;}else{/* ADD / Subtract operation */printf("\r\nAdd/Subtract operation is invalid!\r\n"); return EX_FALSE;}break;case EX_INVERSE_MATRIX:if ((2 == pstMatrixA->ucRow)&& (2 == pstMatrixA->ucCol)){;}else{/* Inverse operation */printf("\r\nMultiply/Inverse operation is invalid!\r\n"); return EX_FALSE;}break;case EX_MULTIPL Y_MATRIX:if ((pstMatrixA->ucRow == pstMatrixB->ucCol)&& (pstMatrixA->ucCol == pstMatrixB->ucRow)) {;}else{/* Multiply operation */printf("\r\nMultiply operation is invalid!\r\n");return EX_FALSE;}break;default:printf("err operate code!\r\n");return EX_FALSE;}return EX_TRUE;}int AddMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC){int iRet = EX_FALSE;unsignedchar ucRow;unsignedchar ucCol;unsignedchar i, j;float fTmpData = 0.0;if ((pstMatrixA == NULL) || (pstMatrixB == NULL)){printf("matrix para is null.\r\n");return EX_FALSE;}iRet = CheckMatrix(iOpCode, pstMatrixA, pstMatrixB);if (EX_FALSE == iRet){return iRet;}else{ucRow = pstMatrixA->ucRow;ucCol = pstMatrixA->ucCol;}/* create result matrix C */iRet = CreateResultMatrix(ucRow, ucCol, pstMatrixC);if (iRet != EX_TRUE){return iRet;}for (i = 0; i < ucRow; i++){for (j = 0; j < ucCol; j++){fTmpData = (*(pstMatrixA->pfDataAdd + i * ucCol + j) + *(pstMatrixB->pfDataAdd + i * ucCol + j));*(pstMatrixC->pfDataAdd + i * ucCol + j) = fTmpData;}}return EX_TRUE;}int SubtractMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC){int iRet = EX_FALSE;unsignedchar ucRow;unsignedchar ucCol;unsignedchar i, j;float fTmpData = 0.0;if ((pstMatrixA == NULL) || (pstMatrixB == NULL)){printf("matrix para is null.\r\n");return EX_FALSE;}iRet = CheckMatrix(iOpCode, pstMatrixA, pstMatrixB);if (EX_FALSE == iRet){return iRet;}else{ucRow = pstMatrixA->ucRow;ucCol = pstMatrixA->ucCol;}/* create result matrix C */iRet = CreateResultMatrix(ucRow, ucCol, pstMatrixC);if (iRet != EX_TRUE){return iRet;}for (i = 0; i < ucRow; i++){for (j = 0; j < ucCol; j++){fTmpData = (*(pstMatrixA->pfDataAdd + i * ucCol + j) - *(pstMatrixB->pfDataAdd + i * ucCol + j));*(pstMatrixC->pfDataAdd + i * ucCol + j) = fTmpData;}}return EX_TRUE;}int MultiplyMatrix(int iOpCode, Matrix_s *pstMatrixA, Matrix_s *pstMatrixB, Matrix_s *pstMatrixC){int iRet = EX_FALSE;unsignedchar ucRow;unsignedchar ucCol;unsignedchar i, j, k;float fTmpData = 0.0;if ((pstMatrixA == NULL) || (pstMatrixB == NULL)){printf("matrix para is null.\r\n");return EX_FALSE;}iRet = CheckMatrix(iOpCode, pstMatrixA, pstMatrixB);if (EX_FALSE == iRet){return iRet;}else{ucRow = pstMatrixA->ucRow;ucCol = pstMatrixB->ucCol;}/* create result matrix C */iRet = CreateResultMatrix(ucRow, ucCol, pstMatrixC);if (iRet != EX_TRUE){return iRet;}for (i = 0; i < ucRow; i++){for (j = 0; j < ucCol; j++){for (k = 0; k < pstMatrixA->ucCol; k++){fTmpData += (float)(*(pstMatrixA->pfDataAdd + i * ucCol + k) * *(pstMatrixB->pfDataAdd + j + k * ucCol));}*(pstMatrixC->pfDataAdd + i * ucCol + j) = fTmpData;fTmpData = 0;}}return EX_TRUE;}int CreateResultMatrix(unsignedchar ucRow, unsignedchar ucCol, void *pvData){Matrix_s *pstTmpData = NULL;int iRet = EX_FALSE;if (pvData == NULL){printf("para is null.\r\n");return EX_FALSE;}else{pstTmpData = (Matrix_s *)pvData;}/* create result matrix C */memset(pstTmpData, 0, sizeof(Matrix_s));pstTmpData->ucRow = ucRow;pstTmpData->ucCol = ucCol;iRet = CreateMatrixMem(pstTmpData);if (iRet != EX_TRUE){printf("err create result Matrix C!\r\n"); return iRet;}return EX_TRUE;}int InverseMatrix(float a[], int n){int *is,*js;int i,j,k,l,u,v;float d, p;is = (int *)malloc(n * sizeof(int));js = (int *)malloc(n * sizeof(int));for (k = 0; k <= n-1; k++){d = 0.0;for (i = k; i <= n-1; i++){ for (j = k; j <= n-1; j++){l = i * n + j;p = (float)fabs(a[l]);if (p > d){d = p;is[k] = i;js[k] = j;}}}if (d + 1.0 == 1.0){free(is);free(js);printf("err not inverse!\r\n"); return EX_FALSE;}if (is[k] != k){ for (j=0; j<=n-1; j++){u = k * n + j;v = is[k] * n +j;p = a[u];a[u] = a[v];a[v] = p;}}if (js[k] != k){for (i=0; i<=n-1; i++){u = i*n+k;v = i*n+js[k];p = a[u];a[u] = a[v];a[v] = p;}}l = k * n + k;a[l] = (float)(1.0 / a[l]);for (j = 0; j <= n-1; j++){if (j != k){u = k * n + j;a[u] = a[u] * a[l];}}for (i = 0; i <= n-1; i++){if (i != k){for (j = 0; j <= n-1; j++){if (j != k){u = i * n + j;a[u] = a[u] - a[i * n + k] * a[k * n + j];}}for (i = 0; i <= n-1; i++){if (i != k){u = i * n + k;a[u] = -a[u] * a[l];}}}}}for (k = n-1; k >= 0; k--){if (js[k] != k)for (j = 0; j <= n-1; j++){u = k * n + j;v = js[k] * n + j;p = a[u];a[u] = a[v];a[v] = p;}if (is[k] != k)for (i = 0; i <= n-1; i++){u = i * n + k;v = i * n + is[k];p = a[u];a[u] = a[v];a[v] = p;}}free(is);free(js);return EX_TRUE;}。
计算器编程c语言
计算器编程 c语言用C语言设计计算器程序源代码#include <dos.h> /*DOS接口函数*/#include <math.h> /*数学函数的定义*/#include <conio.h> /*屏幕操作函数*/函数*/#include <stdio.h> /*I/O#include <stdlib.h> /*库函数*/变量长度参数表*/#include <stdarg.h> /*图形函数*/#include <graphics.h> /*字符串函数*/#include <string.h> /*字符操作函数*/#include <ctype.h> /*#define UP 0x48 /*光标上移键*/#define DOWN 0x50 /*光标下移键*/#define LEFT 0x4b /*光标左移键*/#define RIGHT 0x4d /*光标右移键*/#define ENTER 0x0d /*回车键*/void *rar; /*全局变量,保存光标图象*/使用调色板信息*/struct palettetype palette; /*int GraphDriver; /* 图形设备驱动*/int GraphMode; /* 图形模式值*/int ErrorCode; /* 错误代码*/int MaxColors; /* 可用颜色的最大数值*/int MaxX, MaxY; /* 屏幕的最大分辨率*/double AspectRatio; /* 屏幕的像素比*/void drawboder(void); /*画边框函数*/初始化函数*/void initialize(void); /*计算器计算函数*/void computer(void); /*改变文本样式函数*/ void changetextstyle(int font, int direction, int charsize); /*窗口函数*/void mwindow(char *header); /*/*获取特殊键函数*/int specialkey(void) ;设置箭头光标函数*//*int arrow();/*主函数*/int main(){设置系统进入图形模式 */initialize();/*运行计算器 */computer(); /*系统关闭图形模式返回文本模式*/closegraph();/*/*结束程序*/return(0);}/* 设置系统进入图形模式 */void initialize(void){int xasp, yasp; /* 用于读x和y方向纵横比*/GraphDriver = DETECT; /* 自动检测显示器*/initgraph( &GraphDriver, &GraphMode, "" );/*初始化图形系统*/ErrorCode = graphresult(); /*读初始化结果*/如果初始化时出现错误*/if( ErrorCode != grOk ) /*{printf("Graphics System Error: %s\n",显示错误代码*/grapherrormsg( ErrorCode ) ); /*退出*/exit( 1 ); /*}getpalette( &palette ); /* 读面板信息*/MaxColors = getmaxcolor() + 1; /* 读取颜色的最大值*/MaxX = getmaxx(); /* 读屏幕尺寸 */MaxY = getmaxy(); /* 读屏幕尺寸 */getaspectratio( &xasp, &yasp ); /* 拷贝纵横比到变量中*/计算纵横比值*/ AspectRatio = (double)xasp/(double)yasp;/*}/*计算器函数*/void computer(void){定义视口类型变量*/struct viewporttype vp; /*int color, height, width;int x, y,x0,y0, i, j,v,m,n,act,flag=1;操作数和计算结果变量*/float num1=0,num2=0,result; /*char cnum[5],str2[20]={""},c,temp[20]={""};定义字符串在按钮图形上显示的符号 char str1[]="1230.456+-789*/Qc=^%";/**/mwindow( "Calculator" ); /*显示主窗口 */设置灰颜色值*//*color = 7;getviewsettings( &vp ); /* 读取当前窗口的大小*/width=(vp.right+1)/10; /* 设置按钮宽度 */设置按钮高度 */height=(vp.bottom-10)/10 ; /*/*设置x的坐标值*/x = width /2;设置y的坐标值*/y = height/2; /*setfillstyle(SOLID_FILL, color+3);bar( x+width*2, y, x+7*width, y+height );/*画一个二维矩形条显示运算数和结果*/setcolor( color+3 ); /*设置淡绿颜色边框线*/rectangle( x+width*2, y, x+7*width, y+height );/*画一个矩形边框线*/设置颜色为红色*/setcolor(RED); /*输出字符串"0."*/outtextxy(x+3*width,y+height/2,"0."); /*/*设置x的坐标值*/x =2*width-width/2;设置y的坐标值*/y =2*height+height/2; /*画按钮*/for( j=0 ; j<4 ; ++j ) /*{for( i=0 ; i<5 ; ++i ){setfillstyle(SOLID_FILL, color);setcolor(RED);bar( x, y, x+width, y+height ); /*画一个矩形条*/rectangle( x, y, x+width, y+height );sprintf(str2,"%c",str1[j*5+i]);/*将字符保存到str2中*/outtextxy( x+(width/2), y+height/2, str2);移动列坐标*/x =x+width+ (width / 2) ;/*}y +=(height/2)*3; /* 移动行坐标*/x =2*width-width/2; /*复位列坐标*/}x0=2*width;y0=3*height;x=x0;y=y0;gotoxy(x,y); /*移动光标到x,y位置*/显示光标*/arrow(); /*putimage(x,y,rar,XOR_PUT);m=0;n=0;设置str2为空串*/strcpy(str2,""); /*当压下Alt+x键结束程序,否则执行下面的循环while((v=specialkey())!=45) /**/{当压下键不是回车时*/while((v=specialkey())!=ENTER) /*{putimage(x,y,rar,XOR_PUT); /*显示光标图象*/if(v==RIGHT) /*右移箭头时新位置计算*/if(x>=x0+6*width)如果右移,移到尾,则移动到最左边字符位置*//*{x=x0;m=0;}else{x=x+width+width/2;m++;否则,右移到下一个字符位置*/} /*if(v==LEFT) /*左移箭头时新位置计算*/if(x<=x0){x=x0+6*width;m=4;} /*如果移到头,再左移,则移动到最右边字符位置*/else{x=x-width-width/2;m--;} /*否则,左移到前一个字符位置*/if(v==UP) /*上移箭头时新位置计算*/if(y<=y0){y=y0+4*height+height/2;n=3;} /*如果移到头,再上移,则移动到最下边字符位置*/else{y=y-height-height/2;n--;} /*否则,移到上边一个字符位置*/if(v==DOWN) /*下移箭头时新位置计算*/if(y>=7*height){ y=y0;n=0;} /*如果移到尾,再下移,则移动到最上边字符位置*/else{y=y+height+height/2;n++;} /*否则,移到下边一个字符位置*/putimage(x,y,rar,XOR_PUT); /*在新的位置显示光标箭头*/ }将字符保存到变量c中*/c=str1[n*5+m]; /*判断是否是数字或小数点*/if(isdigit(c)||c=='.') /*{如果标志为-1,表明为负数*/if(flag==-1) /*{将负号连接到字符串中*/strcpy(str2,"-"); /*flag=1;} /*将标志值恢复为1*/将字符保存到字符串变量temp中*/ sprintf(temp,"%c",c); /*将temp中的字符串连接到str2中*/strcat(str2,temp); /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,str2); /*}if(c=='+'){将第一个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算加法标志值*/act=1; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='-'){如果str2为空,说明是负号,而不是减号*/ if(strcmp(str2,"")==0) /*设置负数标志*/flag=-1; /*else{将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*act=2; /*做计算减法标志值*/setfillstyle(SOLID_FILL,color+3);画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}}if(c=='*'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算乘法标志值*/act=3; /*setfillstyle(SOLID_FILL,color+3); bar(2*width+width/2,height/2,15*width /2,3*height/2);显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='/'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算除法标志值*/act=4; /*setfillstyle(SOLID_FILL,color+3);bar(2*width+width/2,height/2,15*width/2,3*height/2);outtextxy(5*width,height,"0."); /*显示字符串*/}if(c=='^'){将第二个操作数转换为浮点数*/num1=atof(str2); /*将str2清空*/strcpy(str2,""); /*做计算乘方标志值*/act=5; /*设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='%'){将第二个操作数转换为浮点数*/num1=atof(str2); /*strcpy(str2,""); /*将str2清空*/做计算模运算乘方标志值*/act=6; /*setfillstyle(SOLID_FILL,color+3); /*设置用淡绿色实体填充*/画矩形*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}if(c=='='){将第二个操作数转换为浮点数*/num2=atof(str2); /*根据运算符号计算*/switch(act) /*{case 1:result=num1+num2;break; /*做加法*/case 2:result=num1-num2;break; /*做减法*/case 3:result=num1*num2;break; /*做乘法*/case 4:result=num1/num2;break; /*做除法*/case 5:result=pow(num1,num2);break; /*做x的y次方*/case 6:result=fmod(num1,num2);break; /*做模运算*/ }设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*将结果保存到temp中*/sprintf(temp,"%f",result); /*outtextxy(5*width,height,temp); /*显示结果*/}if(c=='c'){num1=0; /*将两个操作数复位0,符号标志为1*/num2=0;flag=1;strcpy(str2,""); /*将str2清空*/设置用淡绿色实体填充*/ setfillstyle(SOLID_FILL,color+3); /*覆盖结果区*/ bar(2*width+width/2,height/2,15*width/2,3*height/2); /*显示字符串*/outtextxy(5*width,height,"0."); /*}如果选择了q回车,结束计算程序*/if(c=='Q')exit(0); /*}putimage(x,y,rar,XOR_PUT); /*在退出之前消去光标箭头*/返回*/return; /*}/*窗口函数*/void mwindow( char *header ){int height;cleardevice(); /* 清除图形屏幕 */setcolor( MaxColors - 1 ); /* 设置当前颜色为白色*//* 设置视口大小 */ setviewport( 20, 20, MaxX/2, MaxY/2, 1 );height = textheight( "H" ); /* 读取基本文本大小 */settextstyle( DEFAULT_FONT, HORIZ_DIR, 1 );/*设置文本样式*/settextjustify( CENTER_TEXT, TOP_TEXT );/*设置字符排列方式*/输出标题*/outtextxy( MaxX/4, 2, header ); /*setviewport( 20,20+height+4, MaxX/2+4, MaxY/2+20, 1 ); /*设置视口大小*/ 画边框*/drawboder(); /*}画边框*/void drawboder(void) /*{定义视口类型变量*/struct viewporttype vp; /*setcolor( MaxColors - 1 ); /*设置当前颜色为白色 */setlinestyle( SOLID_LINE, 0, NORM_WIDTH );/*设置画线方式*/将当前视口信息装入vp所指的结构中*/getviewsettings( &vp );/*画矩形边框*/rectangle( 0, 0, vp.right-vp.left, vp.bottom-vp.top ); /*}/*设计鼠标图形函数*/int arrow(){int size;定义多边形坐标*/int raw[]={4,4,4,8,6,8,14,16,16,16,8,6,8,4,4,4}; /*设置填充模式*/setfillstyle(SOLID_FILL,2); /*/*画出一光标箭头*/fillpoly(8,raw);测试图象大小*/size=imagesize(4,4,16,16); /*分配内存区域*/rar=malloc(size); /*存放光标箭头图象*/getimage(4,4,16,16,rar); /*putimage(4,4,rar,XOR_PUT); /*消去光标箭头图象*/return 0;}/*按键函数*/int specialkey(void){int key;等待键盘输入*/while(bioskey(1)==0); /*key=bioskey(0); /*键盘输入*/只取特殊键的扫描值,其余为0*/ key=key&0xff? key&0xff:key>>8; /*return(key); /*返回键值*/}。
行列式的求值(c语言版)
行列式的求值(C语言版)本程序用C语言实现行列式的求值,由于采用的是行列式中最原始的公式求解,其运行效率并不十分高,但可以保证只要电脑能跑下来,就可以算对.本人验证表明,对9阶以内的运行效果还可以.10阶就不好说了.本程序实际上是分二部分,第一部分是程序求0到n-1或1到n的全排列,并采用文件操作,将排列结果保存在一个文件中;第二部分是用数学方法求行列式的值,并从文件中读取排列结果并计算p(a1,a2,a3┈a n).本人设想的另一种办法是采用多线程,当生成一种排列后直接送到计算程序,或计可以加快计算速度.有名的MATLAB计算高阶行列式时(例如80阶)简直是不用眨眼就出来了,不知道用的是什么算法.第一部分的算法已单独的上传在本文揖中,名为<C语言用堆栈0到n-1的全排列>.用户在使用时要将以下5个文件全部编译一遍才行.(本机运行环境是xpsp3+vc6.0++)plzh为排列组合det为行列式.//头文件plzh.h#ifndef PLZH_H#define PLZH_H#include <stdlib.h>#include <stdio.h>void initial(int n);int stackfull(int n);void stackprint(int n);void stackoutfile(int n);void stackback();void stackadd(int n);void stackmov(int n);void stackfun(int n);#endif//plzh.h的实现plzh.c#include <stdlib.h>#include <stdio.h>#include "plzh.h"#define N 50 //定义栈的大小.int stack[N]; //定义栈.int p=-1; //定义栈底.int a[N],b[N],c[N]; //分别表示当前数的值,改变后的值,及改变的次数.FILE *pfile;/***********************对栈进行初始化.**********************/void initial(int n){int i=0;for(i=0;i<n;i++){stack[++p]=i; //第一次初始化的值.a[i]=b[i]=i; //初始值相同.c[i]=0; //0表示尚未改变过.}}/*********************************************** *判断栈是否已满,在本程序中,此函数实际上是多余的.***********************************************/ int stackfull(int n){if(p+1==n)return 1;elsereturn 0;}/*********************打印栈中的数值.*此处是输出到屏幕上.********************/void stackprint(int n){int i=0;for(i=0;i<n;i++)printf("%d ",stack[i]); printf("\n");}/************************* *也可输出到文件中.*************************/void stackoutfile(int n){fwrite(stack,sizeof(int),n,pfile);}/************************退栈.*实际上这个可以省去,但为了更好理解,写成一个函数. ***********************/void stackback(){p--;}/***********************************当经过一次退栈后,当前栈顶是p,则p+1到n-1* 中并没有填充数字,此函数的作用就是为后面* 的栈中重新入栈.*并且此处是有规律的入栈.**********************************/void stackadd(int n){int j,k,flag; //j,k是控制变量,flag是标志变量.while(1+p<n) //一直循环到最后.{/*************************此段的作用是使当前填充的值与前面的都不相同.*用for循环控制.************************/for(j=0;j<n;j++){flag=0;for(k=0;k<=p;k++){if(j==stack[k]) //若与某一个栈相同,则重新对j赋值.{flag=1;break;}}if(flag==0) //当flag为0时,表示赋值成功.{stack[++p]=j; //当此值赋到栈中.a[p]=b[p]=j;//同时重新定义当前值,并使其相等.相当于又初始化.c[p]=0; //把值的改变次数定义为0.break;}}}}/**********************************本程序的核心所在.*算法是若退栈到当前值,则改变当前值.*使当前栈值b[p]=(b[p]+1)%n;*********************************/void stackmov(int n){int flag,i;while(1){b[p]=(b[p]+1)%n; //此处比较好理解,即循环.c[p]++; //记录值的变化.flag=0; //0表示赋值成功,1表示要赋的值已被占用.for(i=0;i<p;i++){if(b[p]==stack[i]) //要赋的值已存在.{flag=1;break;}}if(flag==1) //若赋值失败则进行下一轮的赋值.continue;if((a[p]==b[p])||flag==0) //结果是要么赋值成功,要么回到原来的值.break;}if(flag==0&&(a[p]!=b[p])) //当赋值成功.{stack[p]=b[p]; //将值赋进栈中.stackadd(n); //对该栈后面的值进行填充.}else //当回到原来的位置,要退栈.stackback();}/***********************************此处是接口函数.**********************************/void stackfun(int n){pfile=fopen("dat.ttt","wb");initial(n); //初始化.if(stackfull(n)) //初始化后本身就是一个成功的排列,打印出来.{//stackprint(n);stackoutfile(n);}while(1) //一直循环下去,直到退无可退.{/**********************************这是本程序中最关键的一条指令.*此处的退栈仅且只能在值尚未发生变化的情况下退栈.*若没有c[p]!=0,当退到任一个栈时,他们的初始状态都是a[p]==b[p]*若是(a[p]==b[p])&&c[p]!=0表明当前栈已是退无可退.*此处有个关键时,第一轮开始的时候并没有执行该指令,当栈顶值循环一轮后*使c[p]!=0后才开始执行的,要特别注意这个地方.*********************************/if((a[p]==b[p])&&c[p]!=0)stackback();stackmov(n); //退完栈后要补齐后面的.if(stackfull(n)){//stackprint(n);stackoutfile(n);}if(p==-1) //结束的条件,退无可退.break;}fclose(pfile);}// 行列式求值方法的头文件det.h #ifndef DET_H#define DET_H#include <stdlib.h>#include <stdio.h>void detcal();#endif//det.h 的实现方法det.c#include <stdlib.h>#include <stdio.h>#include "det.h"#include "plzh.h"#define N 20void detcal(){int col[N][N],R[N];int sum,count;int n;int i,j;FILE *pfile;printf("输入行列式的阶(输0退出): "); scanf("%d",&n);if(n==0)exit(0);printf("按行输入行列式的项: ");for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&col[i][j]);stackfun(n);sum=0;pfile=fopen("dat.ttt","rb");/***********************************此处遇到的巨大问题时,最后一行会读二遍,*即feof不是十分管用,所以采用如下策略, *将fread()使用两遍,最后一次将因为提前读, *而被feof()判出界.**********************************/ fread(R,sizeof(int),n,pfile);while(!feof(pfile)){count=0;for(i=0;i<n-1;i++)for(j=i+1;j<n;j++){if(R[i]>R[j])count++;}if(count%2==0)count=1;elsecount=-1;for(i=0;i<n;i++)count*=col[i][R[i]];sum+=count;fread(R,sizeof(int),n,pfile);}fclose(pfile);printf("%d\n",sum);}//下面是用户的应该调用接口即main(). Interface.c #include <stdlib.h>#include <stdio.h>#include "det.h"int main(){for(;;){detcal();printf("\n");}return 0;}。
数据结构——多项式运算器源代码
#include<stdio.h>#include<malloc.h>#include<math.h>#include<stdlib.h>typedef struct{float coef;int expn;}term,ElemType;typedef struct LNode{ElemType data;struct LNode *next;}*Link;typedef struct{Link head,tail;int len;}LinkList;/*====================链表-ADT====================*/ void MakeNode(Link &p,ElemType e){p=(Link)malloc(sizeof(struct LNode));if(!p) exit(1);p->data=e;p->next=NULL;}//MakeNodevoid InitList(LinkList &L){L.head=L.tail=(Link)malloc(sizeof(LNode));if(!L.head) exit(1);L.head->next=NULL;L.len=0;}//InitListvoid DestroyList(LinkList &L){Link p,q;p=L.head->next;while(p){q=p->next;free(p);p=q;}L.head->next=NULL;L.tail=L.head;L.len=0;}//DestroyListvoid InsLast(LinkList &L,Link s){L.tail->next=s;L.tail=s;L.len++;L.tail->next=NULL;}//InsLastvoid Append(LinkList &L,Link s){Link q;int m;if(!s) exit(1);L.tail->next=s;q=s;m=1;while(q->next){m++;q=q->next;}L.len+=m;L.tail=q;}//Append/*====================多项式-ADT====================*/ void CreatPolyn(LinkList &L){term e;Link s;scanf("%f,%d",&e.coef,&e.expn);while(e.coef){MakeNode(s,e);InsLast(L,s);scanf("%f,%d",&e.coef,&e.expn);}L.tail->next=NULL;}//CreatPolynint Judge(int n){if(n>19||n<0){printf("存储位置选择错误!请重新选择0-19.\n");return 1;}elsereturn 0;}//Judgevoid PrintPolyn(LinkList L){Link p;p=L.head->next;if(!p)printf("NULL\n");else {printf("y=");if(p->data.coef>0){if(p->data.expn==0)printf("%f",p->data.coef);elseprintf("%fx^%d",p->data.coef,p->data.expn);p=p->next;}else{if(p->data.expn==0)printf("%f",p->data.coef);elseprintf("%fx^%d",p->data.coef,p->data.expn);p=p->next;}while(p){if(p->data.coef>0){if(p->data.expn==0)printf("+%f",p->data.coef);elseprintf("+%fx^%d",p->data.coef,p->data.expn);p=p->next;}else{if(p->data.expn==0)printf("%f",p->data.coef);elseprintf("%fx^%d",p->data.coef,p->data.expn);if(p->next)p=p->next;}}printf("\n");}}//PrintPolynvoid PrintAll(LinkList S[]){int i;for(i=0;i<20;i++){printf("%d.",i);PrintPolyn(S[i]);}}//PrintAllvoid CopyPolyn(LinkList L,LinkList &S){term e;Link s,p;p=L.head->next;while(p){e.coef=p->data.coef;e.expn=p->data.expn;MakeNode(s,e);InsLast(S,s);p=p->next;}S.tail->next=NULL;}//CopyPolynint AddPolyn(LinkList &L,LinkList P,LinkList Q){ Link a,b,c;term e;a=P.head->next;b=Q.head->next;while((a!=NULL)&&(b!=NULL)){if(a->data.expn<b->data.expn){e.coef=a->data.coef;e.expn=a->data.expn;MakeNode(c,e);InsLast(L,c);a=a->next;}else if(a->data.expn>b->data.expn){e.coef=b->data.coef;e.expn=b->data.expn;MakeNode(c,e);InsLast(L,c);b=b->next;}else if((a->data.coef+b->data.coef)!=0){e.coef=a->data.coef+b->data.coef;e.expn=a->data.expn;MakeNode(c,e);InsLast(L,c);a=a->next;b=b->next;}else if((a->data.coef+b->data.coef)==0){a=a->next;b=b->next;}}if(!a&&!b){L.tail->next=NULL;return 0;}if(!b){while(a){e.coef=a->data.coef;e.expn=a->data.expn;MakeNode(c,e);InsLast(L,c);a=a->next;}}if(!a){while(b){e.coef=b->data.coef;e.expn=b->data.expn;MakeNode(c,e);InsLast(L,c);b=b->next;}}return 0;}//AddPolynvoid SubtractPolyn(LinkList &L,LinkList P,LinkList Q){ Link p;p=Q.head->next;while(p){p->data.coef=0-p->data.coef;p=p->next;}AddPolyn(L,P,Q);p=Q.head->next;while(p){p->data.coef=0-p->data.coef;p=p->next;}}//SubtractPolyndouble ResultPolyn(LinkList L,float x){Link p;double y=0;p=L.head->next;while(p){y+=(pow(x,p->data.expn)*p->data.coef);p=p->next;}return y;}//ResultPolynvoid MultiplyPolyn(LinkList &L,LinkList P,LinkList Q){ Link l,p,q;LinkList E,F;InitList(E);InitList(F);int i,j;term e;p=P.head->next;q=Q.head->next;for(i=0;i<Q.len;i++){for(j=0;j<P.len;j++){e.coef=p->data.coef*q->data.coef;e.expn=p->data.expn+q->data.expn;MakeNode(l,e);InsLast(E,l);p=p->next;}AddPolyn(L,E,F);DestroyList(E);DestroyList(F);CopyPolyn(L,F);if(i!=Q.len-1)DestroyList(L);q=q->next;p=P.head->next;}}//MultiplyPolynvoid Polyn_NFang(LinkList &L,LinkList P,int n){ int i;LinkList E;InitList(E);CopyPolyn(P,E);for(i=0;i<n;i++){MultiplyPolyn(L,E,P);DestroyList(E);CopyPolyn(L,E);if(i!=n-1)DestroyList(L);}}//Polyn_NFangvoid Polyn_NDao(LinkList &L,LinkList P,int n){ Link p,q;int i,j;CopyPolyn(P,L);for(i=0;i<n;i++){p=L.head->next;q=L.head;for(j=0;j<L.len;j++){if(p->data.expn==0){q->next=p->next;free(p);p=q->next;L.len--;}p->data.coef=p->data.coef*p->data.expn;p->data.expn=p->data.expn-1;p=p->next;q=q->next;}}}//Polyn_NDaoint Polyn_Ji(LinkList &L,LinkList P){Link p;int i;CopyPolyn(P,L);p=L.head->next;for(i=0;i<L.len;i++){if(p->data.expn==-1){printf("对不起,本程序不能实现对-1次方的积分.请重新选择.\n");DestroyList(L);return 0;}elsep=p->next;}for(i=0;i<L.len;i++){p->data.coef=p->data.coef/(p->data.expn+1);++p->data.expn;p=p->next;}return 0;}//Polyn_Jidouble Polyn_Ding(LinkList L,float a,float b){double m,n;double e=0;LinkList P;InitList(P);Polyn_Ji(P,L);m=ResultPolyn(P,a);n=ResultPolyn(P,b);e=n-m;return e;}//Polyn_Ding/*====================main====================*/void main(){int n,m,i,a,b,c;float x,e,f;double d;LinkList S[20];for(i=0;i<20;i++)InitList(S[i]);printf("说明:共有二十个多项式备用位置:0~19。
C语言写的一个简单的计算器
C语言写的一个简单的计算器下面是一个简单的C语言计算器代码,该代码具有加法、减法、乘法和除法功能。
要求用户输入两个数字和一个运算符,然后计算并显示结果。
```c#include <stdio.h>int maidouble num1, num2, result;char operator;printf("请输入第一个数字: ");scanf("%lf", &num1);printf("请输入运算符(+、-、*、/): ");scanf(" %c", &operator);printf("请输入第二个数字: ");scanf("%lf", &num2);switch(operator)case '+':result = num1 + num2;printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);break;case '-':result = num1 - num2;printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result); break;case '*':result = num1 * num2;printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result); break;case '/':if(num2 == 0)printf("除数不能为0\n");} elseresult = num1 / num2;printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result); }break;default:printf("无效的运算符\n");break;}return 0;```这个简单的计算器程序首先要求用户输入第一个数字,然后输入一个运算符(+、-、*、/),最后输入第二个数字。
c语言计算n阶行列式
c语言计算n阶行列式
在数学中,行列式是一个非常重要的概念,它是矩阵的一个标量值,可以用来描述矩阵的一些性质。
在计算机领域中,我们常常需要用到行列式,例如在图形学中,行列式可以用来计算逆矩阵和平移、旋转、缩放等变换。
本文将介绍如何使用C语言计算n阶行列式。
首先,我们需要了解什么是行列式。
行列式通常用“det”表示,它是一个方阵的一个标量值。
对于n阶方阵A,它的行列式可以表示为:
det(A) = Σ[(-1)^i+j * aij * det(Aij)]
其中,i和j表示A中元素的行和列,aij表示A中第i行第j 列的元素,Aij表示去掉第i行第j列后得到的n-1阶方阵。
根据上述公式,我们可以递归地计算行列式。
当方阵为1阶时,行列式等于该方阵中的元素值;当方阵为2阶时,行列式等于a11*a22-a12*a21;当方阵为3阶时,行列式等于
a11*a22*a33+a12*a23*a31+a13*a21*a32-a11*a23*a32-
a12*a21*a33-a13*a22*a31,依此类推。
现在,我们可以使用C语言来实现计算n阶行列式的程序。
具体步骤如下:
1.定义一个函数来计算n阶行列式,函数名为det,参数为一个n阶二维数组。
2.通过递归的方式计算行列式。
当n为1时,直接返回该元素
的值;当n为2时,使用上述公式计算行列式;当n大于2时,对于每个元素,计算其代数余子式,并计算出该元素对应的余子式的行列式,最终将所有结果相加。
3.在程序中调用该函数,并输入要计算的n阶方阵。
矩阵计算C语言源代码
矩阵计算C语言源代码下面是一个简单的矩阵计算的C语言源代码:```c#include <stdio.h>//函数声明void addMatrix(int rows, int columns, int matrixA[][columns], int matrixB[][columns], int result[][columns]);void multiplyMatrix(int rows, int columnsA, int columnsB,int matrixA[][columnsA], int matrixB[][columnsB], intresult[][columnsB]);void printMatrix(int rows, int columns, intmatrix[][columns]);int maiint rows, columns;//输入矩阵的行数和列数printf("Enter the number of rows in the matrices: ");scanf("%d", &rows);printf("Enter the number of columns in the matrices: ");scanf("%d", &columns);int matrixA[rows][columns], matrixB[rows][columns], sumMatrix[rows][columns], productMatrix[rows][columns];//输入矩阵A的元素printf("Enter the elements of matrix A:\n");for (int i = 0; i < rows; i++)for (int j = 0; j < columns; j++)scanf("%d", &matrixA[i][j]);}}//输入矩阵B的元素printf("Enter the elements of matrix B:\n");for (int i = 0; i < rows; i++)for (int j = 0; j < columns; j++)scanf("%d", &matrixB[i][j]);}}//计算两个矩阵的和addMatrix(rows, columns, matrixA, matrixB, sumMatrix);//计算两个矩阵的乘积multiplyMatrix(rows, columns, columns, matrixA, matrixB, productMatrix);printf("Sum of the matrices:\n");printMatrix(rows, columns, sumMatrix);printf("Product of the matrices:\n");printMatrix(rows, columns, productMatrix);return 0;//函数定义:将两个矩阵相加void addMatrix(int rows, int columns, int matrixA[][columns], int matrixB[][columns], int result[][columns])for (int i = 0; i < rows; i++)for (int j = 0; j < columns; j++)result[i][j] = matrixA[i][j] + matrixB[i][j];}}//函数定义:将两个矩阵相乘void multiplyMatrix(int rows, int columnsA, int columnsB,int matrixA[][columnsA], int matrixB[][columnsB], intresult[][columnsB])for (int i = 0; i < rows; i++)for (int j = 0; j < columnsB; j++)result[i][j] = 0;for (int k = 0; k < columnsA; k++)result[i][j] += matrixA[i][k] * matrixB[k][j];}}}//函数定义:打印矩阵void printMatrix(int rows, int columns, intmatrix[][columns])for (int i = 0; i < rows; i++)for (int j = 0; j < columns; j++)printf("%d ", matrix[i][j]);}printf("\n");}```该程序首先要求用户输入两个矩阵的行数和列数,然后用户根据提示分别输入两个矩阵的元素。
c语言 矩阵计算器
}
};break;
case 4://矩阵转置
{
printf("请输入矩阵A的行数和列数(用逗号隔开):");
scanf("%d,%d",&i,&j);
printf("请输入矩阵A:\n");//输入矩阵A的元素
for(p=0;p<i;p++)
for(q=0;q<j;q++)
int x;
do{
printf("请选择您需要的运算,若退出则选择0后按回车键结束\n");
printf("******************************************************************\n");
printf("0,退出\n");
printf("1,矩阵相加\n");
switch (x)
{
case 0:
printf("谢谢您使用该系统!");
break; //退出系统
case 1: //选择加法运算
{
printf("请输入矩阵A的行数和列数(用逗号隔开):");
scanf("%d,%d",&i,&j);
printf("请输入矩阵B的行数和列数(用逗号隔开):") ;
scanf("%d,%d",&m,&n);
}
printf("请输入矩阵A:\n");//输入矩阵A的元素
矩阵计算器代码实现 C语言
#include<iostream>#include<stdlib.h>#include<math.h>#define N 10 //定义方阵的最大阶数为10#include <iomanip>using namespace std;double MatDet(double *p, int n); //求矩阵的行列式double Creat_M(double *p, int m, int n, int k); //求矩阵元素A(m, n)的代数余子式void print(double *p, int n); //输出矩阵n*nclass Matrix{private:int row,col;double **eM ;public:creatM();//创造矩阵outM(Matrix A);//输出矩阵add(Matrix A,Matrix B);//矩阵相加minus(Matrix A,Matrix B);//矩阵相减transpose(Matrix A);//矩阵转置mutiply(Matrix A,Matrix B);//矩阵相乘h(Matrix A);//求行列式,和上三角inverse(Matrix A);//矩阵的逆};void main(){cout<<"******矩阵计算器******"<<endl;cout<<"请选择你要进行的操作"<<"\n"<<"1:相加2:相减3:转置4:相乘5:求行列式和上三角6:求逆"<<endl;int c;cin>>c;switch(c){case 1:{Matrix m1,m2;cout<<"请输入第一个矩阵"<<endl;m1.creatM();cout<<"请输入第二个矩阵"<<endl;m2.creatM();m1.add(m1,m2);break;}case 2:{Matrix m1,m2;cout<<"请输入第一个矩阵"<<endl;m1.creatM();cout<<"请输入第二个矩阵"<<endl;m2.creatM();m1.minus(m1,m2);break;}case 3:{Matrix A;A.transpose(A);break;}case 4:{Matrix m1,m2;cout<<"请输入第一个矩阵"<<endl;m1.creatM();cout<<"请输入第二个矩阵"<<endl;m2.creatM();m1.mutiply(m1,m2);break;}case 5:{Matrix m;cout<<"请输入矩阵"<<endl;m.creatM();m.h(m);break;}case 6:{double *buffer, *p; //定义数组首地址指针变量int row, num; //定义矩阵的行数和矩阵元素个数int i, j;double determ; //定义矩阵的行列式double a[N][N], b[N][N];int n;cout << "采用逆矩阵的定义法求矩阵的逆矩阵!\n";cout << "请输入矩阵的行数: ";cin >> row;num = 2 * row * row;buffer = (double *)calloc(num, sizeof(double)); //分配内存单元p = buffer;if (NULL != p){for (i = 0; i < row; i++){cout << "Please input the number of " << i+1 << " row: ";for (j = 0; j < row; j++){cin >> *p++;}}}else{cout << "无法分配内存\n";}cout << "The original matrix : \n";print(buffer, row); //打印该矩阵determ = MatDet(buffer, row); //求整个矩阵的行列式p = buffer + row * row;if (determ != 0){cout << "The determinant of the matrix is " << determ << endl;for (i = 0; i < row; i++) //求逆矩阵{for (j = 0; j < row; j++){*(p+j*row+i) = (double)Creat_M(buffer, i, j, row)/determ;}}cout << "The inverse matrix is: " << endl;print(p, row); //打印该矩阵}else{cout << "The determinant is 0, and there is no inverse matrix!\n"; }free(buffer); //释放内存空间getchar();break;}}}Matrix::creatM(){cout<<"请依次输入矩阵的行和列"<<endl;cin>>row>>col;eM=(double**) malloc(row*sizeof(double*)) ;for(int i=0; i<row; i++)eM[i] = (double *)malloc(col * sizeof(double));cout<<"请输入矩阵"<<endl;for( i=0;i<row;i++){for(int j=0;j<col;j++)cin>>eM[i][j] ;}}Matrix::outM(Matrix A){for(int i=0;i<row;i++){for(int j=0;j<col;j++)cout<<eM[i][j]<<" ";cout<<endl;}}Matrix::add(Matrix A, Matrix B){if(A.col!=B.col || A.row!=B.row){cout<<"行列不同"<<endl;}else{for(int i=0;i<A.row;i++){for(int j=0;j<A.col;j++){A.eM[i][j]=A.eM[i][j]+B.eM[i][j];}}cout<<"结果为:\n";A.outM(A);}}Matrix::minus(Matrix A, Matrix B){if(A.col!=B.col || A.row!=B.row){cout<<"行列不同"<<endl;}else{for(int i=0;i<A.row;i++){for(int j=0;j<A.col;j++){A.eM[i][j]=A.eM[i][j]+B.eM[i][j];}}cout<<"结果为:\n";A.outM(A);}}Matrix::transpose(Matrix A){int i,j;cout<<"请输入矩阵"<<endl;A.creatM();cout<<"原矩阵为:\n";A.outM(A);Matrix R;R.row=A.col;R.col=A.row;R.eM=(double**) malloc(R.row*sizeof(double*)) ;for( i=0; i<R.row; i++)R.eM[i] = (double *)malloc(R.col * sizeof(double));for(i=0;i<R.row;i++){for(int j=0;j<R.col;j++){R.eM[i][j]=0;}}for(i=0;i<R.row;i++){for(int j=0;j<R.col;j++){R.eM[i][j]=A.eM[j][i];}}cout<<"结果为:"<<endl;R.outM(R);}Matrix::mutiply(Matrix A, Matrix B){if(A.col!=B.row){cout<<"不能相乘"<<endl;}else{int i;Matrix R;R.row=A.row;R.col=B.col;R.eM=(double**) malloc(R.row*sizeof(double*)) ;for( i=0; i<row; i++)R.eM[i] = (double *)malloc(R.col * sizeof(double));for(i=0;i<R.row;i++){for(int j=0;j<R.col;j++){R.eM[i][j]=0;}}for(i=0;i<R.row;i++){for(int j=0;j<R.col;j++){for(int k=0;k<A.col;k++){R.eM[i][j]+=A.eM[i][k]*B.eM[k][j];}}}cout<<"结果为:\n"<<endl;R.outM(R);}}Matrix::h(Matrix A){if(A.col!=A.row){cout<<"不是方阵"<<endl;}else{int ii,jj,k,u;int iter = 0; //记录行变换的次数(交换)double det1=1,yin;int n=A.row;for(ii=0 ; ii<n; ii++){if(A.eM[ii][ii] == 0)for(jj=ii; jj<n; jj++){if(A.eM[jj][ii] != 0){double temp1;for(int i=0 ; i<n ; i++);{temp1 = A.eM[ii][i];A.eM[ii][i] = A.eM[jj][i];A.eM[ii][i] = temp1;}iter ++;}}for(k=ii+1; k<n; k++){yin = -1 * A.eM[k][ii] / A.eM[ii][ii] ;for(u=0; u<n; u++){A.eM[k][u] = A.eM[k][u] + A.eM[ii][u] * yin;}}}for(ii=0; ii<n; ii++) //求对角线的积即行列式的值det1 = det1 * A.eM[ii][ii];//行变换偶数次符号不变if(iter%2 == 1)det1= -det1;cout<<"矩阵的行列式的值为:"<<det1<<endl;cout<<"转换的上三角矩阵为:"<<endl;for(int i=0; i<n; i++){for(int j=0; j<n; j++){cout<<" "<<A.eM[i][j];}cout<<endl;}cout<<endl;}}double MatDet(double *p, int n){int ii,jj,k,u;int iter = 0; //记录行变换的次数(交换)double det1=1,yin;for(ii=0 ; ii<n; ii++){if(*(p+ii*n+ii) == 0)for(jj=ii; jj<n; jj++){if(*(p+jj*n+ii) != 0){double temp1;for(int i=0 ; i<n ; i++){temp1 = *(p+ii*n+i);*(p+ii*n+i) = *(p+jj*n+i);*(p+ii*n+i) = temp1;}iter ++;}}for(k=ii+1; k<n; k++){yin = -1 * (*(p+k*n+ii)) / (*(p+ii*n+ii)) ;for(u=0; u<n; u++){*(p+k*n+u) = *(p+k*n+u) + *(p+ii*n+u) * yin;}}}for(ii=0; ii<n; ii++) //求对角线的积即行列式的值det1 = det1 * (*(p+ii*n+ii));//行变换偶数次符号不变if(iter%2 == 1)det1= -det1;return det1;}//----------------------------------------------------------------------------//功能: 求k*k矩阵中元素A(m, n)的代数余之式//入口参数: k*k矩阵的首地址,矩阵元素A的下标m,n,矩阵行数k//返回值: k*k矩阵中元素A(m, n)的代数余之式//----------------------------------------------------------------------------double Creat_M(double *p, int m, int n, int k){int len,t;int i, j;double mid_result = 0;int sign = 1;double *p_creat, *p_mid;len = (k-1)*(k-1); //k阶矩阵的代数余之式为k-1阶矩阵p_creat = (double*)calloc(len, sizeof(double)); //分配内存单元p_mid = p_creat;for (i = 0; i < k; i++){for (j = 0; j < k; j++){if (i != m && j != n) //将除第i行和第j列外的所有元素存储到以p_mid为首地址的内存单元{*p_mid++ = *(p+i*k+j);}}}sign = ((m+n)%2 == 0 ? 1 : -1);//代数余之式前面的正、负号t=MatDet(p_creat, k-1);mid_result = sign*t;return mid_result;free(p_creat);}//-----------------------------------------------------//功能: 打印n*n矩阵//入口参数: n*n矩阵的首地址,矩阵的行数n//返回值: 无返回值//-----------------------------------------------------void print(double *p, int n){int i, j;for (i = 0; i < n; i++){cout << setw(4);for (j = 0; j < n; j++){cout << setiosflags(ios::right) << *p++ << setw(10);}cout << endl;}}。
C语言计算器程序源代码
C语⾔计算器程序源代码//strcmp(s1,s2) 当s1⼤于s2时,返回1 ,s1⼩于s2时,返回-1,相等时,返回0 #include "stdio.h"#include "ctype.h"#include "string.h"#include "math.h"#define MAX 256#define STACK_SIZE 128#define WORD_LEN 8#define POP 1#define PUSH 0#define ERR -1#define END 2#define OPER 0#define NUM 1#define WORD 2#define ADD 1#define SUB 2#define MUL 3#define DIV 4#define POW 5#define FAC 6#define BRA_L 7#define BRA_R 8#define SIN 9#define COS 10#define TAN 11#define CTG 12#define LG 13 //以10为底的常⽤对数//#define LN 14//#define LOG 15//⾏标为当前操作符代号,列标为栈顶元素代号//2表⽰计算结束,0表⽰当前操作符进栈,1表⽰栈顶操作符出栈// \0 + - * / ^ ! ( ) sin cos tg ctg lgint Priority[14][14]={2, 1, 1, 1, 1, 1, 1,-1,-1, 1, 1, 1, 1, 1, /* \0 */0, 1, 1, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* + */0, 1, 1, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* - */0, 0, 0, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* * */0, 0, 0, 1, 1, 1, 1, 0,-1, 1, 1, 1, 1, 1, /* / */0, 0, 0, 1, 1, 1, 1, 0,-1, 0, 0, 0, 0, 0, /* ^ */0, 0, 0, 0, 0, 0, 1, 0,-1, 0, 0, 0, 0, 0, /* ! */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* ( */-1,1, 1, 1, 1, 1, 1, 1,-1, 1, 1, 1, 1, 1, /* ) */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* sin */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* cos */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* tg */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0, /* ctg */0, 0, 0, 0, 0, 0,-1, 0,-1, 0, 0, 0, 0, 0}; /* lg */char KeyWord[36][WORD_LEN+1]={"sin", //前12个为函数,多余的⽤于扩展"cos","tan","tg","ctg","lg","","","","","","","","","","help", // 后⾯为命令,多余的为扩展"version","set","digit", //精度,⼩数点后的位数"color","radian", //弧度"degree", //⾓度"file","clr","clear","window", //窗⼝模式"fullscr", //全屏模式"","","","","","","","",""};int OperCode(char c){int code;switch(c){case '\0':code=0;break;case '+':code=1;break;case '-':code=2;break;case '*':code=3;break;case '/':code=4;break;case '^':code=5;break;case '!':code=6;break;case '(':code=7;break;case ')':code=8;break;case 's':code=9;break; //sincase 'c':code=10;break; //coscase 't':code=11;break; //tgcase 'C':code=12;break; //ctgcase 'l':code=13;break; //log default:code=-1;break;};return code;}int WordCode(char* word){int i;for(i=0;i<25;i++)if(strcmp(KeyWord[i],word)==0) break;if(i>=25)return -1;else}void help(){printf("显⽰帮助信息!\n");return;}void version(){printf("显⽰版本信息!\n");return;}void Err(int errcode,int position,char *p){printf("\n ERR:%d Position:%d %s",errcode,position,p); return;}double long factorial(int i){if(i==1 || i==0)return(1.0);elsereturn(i*factorial(i-1));}main(){char Expression[MAX+1];int Operator[STACK_SIZE];int OperStackTop;double long Number[STACK_SIZE];int NumStackTop;double long NumList[STACK_SIZE];int NumCursor,NumListSize;int OperList[STACK_SIZE];int OperCursor,OperListSize;int WordList[STACK_SIZE];int WordCursor,WordListSize;int Index[MAX+1];int IndexCursor,IndexSize;char Word[WORD_LEN+1];double long num,num1,num2,weight,tempnum;int Oper;int isDecimal,isErr,isNumber,isEnd;char CurrentOper;int i,j,k,m,n;char ch;num=0.0;num2=0.0;tempnum=0.0;Oper=-1;while(1){for(i=0;i<=MAX;i++) //表达式初始化,中间表索引初始化{Expression[i]='\0';Index[i]=-1;}for(i=0;i{Operator[i]='0';Number[i]=0.0;NumList[i]=0.0;OperList[i]=-1;WordList[i]=-1;}NumStackTop=-1; //栈顶指针初始化OperStackTop=0; //操作符栈压⼊\0Operator[OperStackTop]=OperCode('\0');NumCursor=0; //各种中间表指针初始化,各种中间表的长度初始化NumListSize=0;OperCursor=0;OperListSize=0; //操作符表中先写⼊第⼀个操作符'\0'WordCursor=0;WordListSize=0;IndexCursor=0;IndexSize=0;// Index[0]=OPER;printf("Cal>"); //初始化完成,输出提⽰符i=0;while((ch=getchar())!='\n'){if(i>MAX) /*输⼊超长,则出错*/{Err(0,i,"输⼊的表达式长度超过规定值!\n");isErr=1;break;}if(isupper(ch))ch=tolower(ch);Expression[i]=ch;i++;}if(isErr==1){isErr=0;continue;}if(strlen(Expression)==0) //直接回车continue;if(strcmp("end",Expression)==0 ||strcmp("exit",Expression)==0 || strcmp("quit",Expr ession)==0)break;//⼀下代码为编译预处理,主要处理负号,并检查括号是否配对k=0;for(i=0;Expression[i]!='\0';i++){if((i==0&&Expression[i]=='-') || (i>0&&Expression[i]=='-'&&Expression[i-1]=='(')){for(j=strlen(Expression);j>i;j--)Expression[j]=Expression[j-1];Expression[i]='0';}if(Expression[i]=='(') //检查括号k++;if(Expression[i]==')')k--;}if(k>0) //如果括号不配对{Err(1,-1,"缺少右括号 )\n");continue;}if(k<0){Err(1,-1,"缺少左括号 (\n");continue;}//编译预处理结束i=0; //词法分析while(1){if(Expression[i]=='\0'){OperList[OperListSize]=OperCode(Expression[i]);OperListSize++;Index[IndexSize]=OPER;IndexSize++;// printf("IndexSize=%d,Index[IndexSize]=%d,Expression[i]=%c\n",IndexSize,Index[IndexSize],Expression[i]); break;}isDecimal=0;isNumber=0;while(isdigit(Expression[i])||Expression[i]=='.') //读取数字{isNumber=1;if(Expression[i]=='.'){if((i<(MAX-1) && !isdigit(Expression[i+1])) || (i+1)==MAX) //不正确的⼩数点位置{Err(2,i,"⼩数点位置不正确!\n");isErr=1;isNumber=0;i++;break;}isDecimal=1;weight=0.1;i++;continue;}if(isDecimal==0)num=num*10.0+(double long)(Expression[i]-'0');{num=num+(double long)(Expression[i]-'0')*weight;weight=weight*0.1;}i++;} //数字读完if(isErr==1)break;if(isNumber==1) //如果刚才成功读取了数字,则数字⼊栈{NumList[NumListSize]=num;NumListSize++;isNumber=0;num=0.0;Index[IndexSize]=NUM;// printf("IndexSize=%d,Index[IndexSize]=%d\n",IndexSize,Index[IndexSize]); IndexSize++;}for(k=0;k<=WORD_LEN;k++)Word[k]='\0';j=0;while(isalpha(Expression[i])){if(j>=WORD_LEN) //超过长度仍然未匹配,则出错{Err(3,i,"单词长度超过规定值/未定义的单词:");printf("%s\n",Word);isErr=1;break;}Word[j]=Expression[i];j++;// printf("WORD:%s\n",Word);if(WordCode(Word)==-1) //匹配不成功{if(!isalpha(Expression[i+1]))//匹配不成功,但是下⼀个字符已经不是字母,{Err(4,i,"未定义的单词:"); //则出错,并跳出循环printf("%s\n",Word);isErr=1;break;} //匹配不成功且还能继续读取字符,则继续读取下⼀个字母i++;continue;}else //匹配成功,则单词⼊表,读取下⼀个字符{switch(WordCode(Word)){case 0:ch='s';break;case 1:ch='c';break;case 2:case 3:ch='t';break;case 4:ch='C';case 5:ch='l';break;default:ch='\0';WordList[WordListSize]=WordCode(Word);WordListSize++;Index[IndexSize]=WORD;IndexSize++;break;};if(ch!='\0'){OperList[OperListSize]=OperCode(ch);OperListSize++;Index[IndexSize]=OPER;IndexSize++;}i++;break;}} //单词读完if(isErr==1)break;if(Expression[i]==' ')i++;if(!isdigit(Expression[i]) && !isalpha(Expression[i]) && Expression[i]!='\0') {if(OperCode(Expression[i])==-1){isErr=1;Err(5,i,"未定义的操作符:");printf("%c\n",Expression[i]);break;}else{OperList[OperListSize]=OperCode(Expression[i]);OperListSize++;Index[IndexSize]=OPER;IndexSize++;i++;}} //操作符读完if(isErr==1)break;} //词法分析结束if(isErr==1){isErr=0;continue;}/* for(k=0;kprintf("NumList[%d]=%f\n",k,NumList[k]);for(k=0;kprintf("OperList[%d]=%d\n",k,OperList[k]);for(k=0;kprintf("WordList[%d]=%d\n",k,WordList[k]);for(k=0;kprintf("Index[%d]=%d\n",k,Index[k]);printf("\n\n IndexCursor=%d IndexSize=%d,\n",IndexCursor,IndexSize);printf("OperStacktop=%d,Operator[OperStackTop]=%d,NumStackTop=%d\n",OperStackTop,Operator[OperStackTop],NumStackTop); // continue;*/isEnd=0;IndexCursor=0;while(1){if(Index[IndexCursor]==NUM){if(NumCursor<0 || NumListSize<0){Err(10,-1,"索引列表与操作数列表信息不匹配\n");isErr=1;break;}NumStackTop++;Number[NumStackTop]=NumList[NumCursor];NumCursor++;IndexCursor++;continue;} //数字处理if(Index[IndexCursor]==OPER){m=OperList[OperCursor];n=Operator[OperStackTop];switch(Priority[m][n]){case ERR:Err(20,IndexCursor,"不可预见的错误!\n");isErr=1;break;case PUSH:OperStackTop++;Operator[OperStackTop]=m;OperCursor++;IndexCursor++;break;case END:isEnd=1;break;case POP:Oper=Operator[OperStackTop];OperStackTop--;switch(Oper){case BRA_L: IndexCursor++;OperCursor++;break;case ADD:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1+num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(11,IndexCursor,"加法运算缺少操作数!\n");isErr=1;}break;case SUB:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1-num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(12,IndexCursor,"减法运算缺少操作数!\n");isErr=1;}break;case MUL:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;num1=Number[NumStackTop];NumStackTop--;tempnum=num1*num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(13,IndexCursor,"乘法运算缺少操作数!\n");isErr=1;}break;case DIV:if(NumStackTop>=1){num2=Number[NumStackTop];NumStackTop--;if(num2==0.0){Err(14,IndexCursor,"除数为 0 ,不能进⾏除法运算!\n"); isErr=1;break;}num1=Number[NumStackTop];NumStackTop--;tempnum=num1/num2;NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(15,IndexCursor,"除法运算缺少操作数!\n"); isErr=1;}break;case POW:if(NumStackTop>=1){num2=Number[NumStackTop]; NumStackTop--;num1=Number[NumStackTop]; NumStackTop--;tempnum=pow(num1,num2); NumStackTop++;Number[NumStackTop]=tempnum;num1=0.0;num2=0.0;tempnum=0.0;}else{Err(16,IndexCursor,"乘⽅运算缺少操作数!\n"); isErr=1;}break;case FAC:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=factorial(num2); NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(17,IndexCursor,"阶乘运算缺少操作数!\n"); isErr=1;}break;case SIN:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=sin(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}{Err(18,IndexCursor,"正弦函数缺少参数!\n"); isErr=1;}break;case COS:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=cos(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(19,IndexCursor,"余弦函数缺少参数!\n"); isErr=1;}break;case TAN:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=tan(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(20,IndexCursor,"正切函数缺少参数!\n");isErr=1;}break;case CTG:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;tempnum=1.0/tan(num2); NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(21,IndexCursor,"余切函数缺少参数!\n"); isErr=1;}break;/* case LN:if(NumStackTop>=0)num2=Number[NumStackTop]; NumStackTop--;if(num2<=0.0){Err(20,IndexCursor,"⾃然对数函数真数:"); printf(" %f ⼩于0!\n",num2);isErr=1;break;}tempnum=log(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(17,IndexCursor,"⾃然对数函数缺少参数!\n"); isErr=1;}break; */case LG:if(NumStackTop>=0){num2=Number[NumStackTop]; NumStackTop--;if(num2<=0.0){Err(23,IndexCursor,"常⽤对数函数真数:"); printf(" %f ⼩于0!\n",num2);isErr=1;break;}tempnum=log10(num2);NumStackTop++;Number[NumStackTop]=tempnum;num2=0.0;tempnum=0.0;}else{Err(22,IndexCursor,"常⽤对数函数缺少参数!\n"); isErr=1;}break;default:Err(100,IndexCursor,"运算符(代码:"); printf(" %d )暂不⽀持!\n",Oper);isErr=1;break;/*#define SIN 9#define COS 10#define TAN 11#define CTG 12#define LOG 13 */}; //switch 语句结束break;};//switchif(isErr==1 || isEnd==1)break;continue;} //运算符处理if(Index[IndexCursor]==WORD){printf(" 单词尚未处理!\n");break;}//在这⾥处理单词}//核⼼计算结束if(isErr==1){isErr=0;continue;}if(NumStackTop>0){Err(1000,-1,"多余的操作数:");printf("%f!\n",Number[NumStackTop]);}elseif(NumStackTop==0 && isEnd==1){if(fabs(Number[NumStackTop])>1e20) printf(" %.20e\n",Number[NumStackTop]); elseprintf(" %f\n",Number[NumStackTop]); isEnd=0;}}//主循环结束}//主函数结束。
C语言实现计算器,附源码,超简单!
20
// 下面这得注意,接收double型的数据得用lf%,接收float用f%
21
scanf("%lf",&x1);
22
23
printf("请输入运算操作(+ - * /):\n");
24
m = getche();
25
printf("\n");
26
27
printf("请输入第二个数:\n");
28
40
result = x1 - x2;
41
printf("%lf - %lf = %lf\n",x1,x2,result);
42
break;
43
44
case '*':
45
printf("乘法\n");
46
result = x1 * x2;
47
printf("%lf * %lf = %lf\n",x1,x2,result);
scanf("%lf",&x2);
29
30
switch(m)
31
{
32
case '+':
33
printf("加法\n");
34
result = x1 + x2;
35
printf("%lf + %lf = %lf\n",x1,x2,result);
36
break;
37
38
case '-':
行列式求解
C++行列式计算程序c++编程用定义法求矩阵的逆矩阵时,要求矩阵行列式值。
编行列式求解程序时可利用行列式的运算性质简化编程。
本文附录所示行列式计算程序(函数)为利用了行列式几个性质,如任意互换行列式两行(列),行列式变号,把第j行(列)元的k倍加到第i行(列)对应元上,行列式值不变等,把行列式化为上三角行列式,方便求解。
为了提高求解的精确性,在化简过程中采用了列选主元法,保证主对角元最大(行列式非零,主对角元非零)。
经验证,算法运行正确。
附:c++行列式求解程序(函数接受一维待求方阵及其阶数,返回方阵行列式值)#include "math.h"float hlsqj(float infz[],int n){float aa[200][200];for(int tt=0;tt<n;tt++)for(int rr=0;rr<n;rr++){aa[tt][rr]=infz[n*tt+rr];}float bb[200];float hls=1;int i,j,k;int khh=0;float temp;float kbs;int a_maxcnt;float a_max;int flag_zero=0;for(i=0;i<n;i++){a_max=fabs(aa[i][i]);a_maxcnt=i;for(int i_100=i;i_100<n-1;i_100++){if(a_max<fabs(aa[i_100+1][i])){a_maxcnt=i_100+1;}}if(a_maxcnt!=i){for(int p=0;p<n;p++){bb[p]=aa[a_maxcnt][p];aa[a_maxcnt][p]=aa[i][p];aa[i][p]=bb[p];}khh++;}if(aa[i][i]!=0){for(j=i+1;j<n;j++){kbs=aa[j][i]/aa[i][i];for(k=0;k<n;k++){temp=aa[j][k]-kbs*aa[i][k];aa[j][k]=temp;}}}else{flag_zero=1;break;}}if(flag_zero==1)hls=0;else{for(i=0;i<n;i++)hls*=aa[i][i];float sign=pow(-1,khh);hls*=sign;}return hls; }。
C#行列式,矩阵的各种算法
C#行列式,矩阵的各种算法using System;using System.Collections.Generic;using System.Linq;using System.Text;//自己写的一个关于矩阵各种计算的算法,还有行列式的各种算法//简单的几步,,,嘿嘿嘿,特意分享下namespace Task1{class JuZhen{public double[,] arr; //矩阵的成员变量private int row, col;public double sum = 0.0;public JuZhen(){ }public JuZhen(int a, int b){row = a;col = b;}/*public void setRC(int a, int b){row = a;col = b;}public int getR(){return row;}public int getC(){return col;}*/public double[,] InputArr(int x, int y) //矩阵的输入函数,用于输入函数并且将输入的函数显示出来{arr = new double[x, y];for (int a = 0; a < x; a++)for (int b = 0; b < y; b++)arr[a, b] = double.Parse(Console.ReadLine());Console.WriteLine("输入的矩阵为:");OutPrint(arr, x, y); //矩阵的显示return arr; //返回输入的矩阵}public void OutPrint(double[,] x, int a, int b) //矩阵的输出函数,调用此函数实现矩阵的输出{for (int i = 0; i < a; i++){for (int j = 0; j < b; j++){Console.Write("{0} ", x[i, j]);}Console.WriteLine(""); //输完一行后换行}}public double[,] QiuYuZiShi(double[,] x, int a) //求行列式的代数余子式矩阵,{double[,] temp;double[,] result = new double[a, a];for (int i = 0; i < a; i++) //i,m两个for 循环对x矩阵遍历,求代数余子式{for (int m = 0; m < a; m++){temp = new double[a - 1, a - 1]; //生成余子式数组for (int j = 0; j < a - 1; j++) //j为余子式列,i为行for (int k = 0; k < a - 1; k++){if(j < i && k < m) //判断构造的元素在去掉的列前面还是后面行的上面还是下面temp[k, j] = x[k, j];if (j < i && k >= m)temp[k, j] = x[k + 1, j];if (j >= i && k < m)temp[k, j] = x[k, j + 1];if (j >= i && k >= m)temp[k, j] = x[k + 1, j + 1];}double s = Math.Pow(-1, i + m); //计算余子式的符号result[i, m] = s * QiuZhi(temp, a - 1); //得代数余子式的一项}}return result;}public double QiuZhi(double[,] x, int a) //行列式的值函数{double[,] temp; //声明临时矩阵数组double s = 1.0; //用他来控制余子式的符号double result = 0.0; //声明临时存储矩阵行列式变量和符号变量if (a == 1){return x[0, 0] * s;}for (int i = 0; i < a; i++){temp = new double[a - 1, a - 1]; //给余子式数组分配空间for (int j = 0; j < a - 1; j++) //j为余子式列,i为行for (int k = 0; k < a - 1; k++){if(j < i) //判断构造的元素在去掉的列前面还是后面temp[k, j] = x[k + 1, j];elsetemp[k, j] = x[k + 1, j + 1];}s = Math.Pow(-1, i); //计算余子式的符号result += x[0, i] * QiuZhi(temp, a - 1) * s; //用递归算法计算行列式的值}return result;}public void Add(double[,] x, int a, int b, double[,] y, int c, int d) //矩阵的相加并且显示相加后的结果{double[,] result = new double[a, b]; //将相加后的矩阵存放在result矩阵中if (a != c || b != d) //对是否能进行乘法进行判断Console.WriteLine("不是同型矩阵,不能进行加法运算");else{for (int i = 0; i < a; i++)for (int j = 0; j < b; j++)result[i, j] = x[i, j] + y[i, j];Console.WriteLine("矩阵相加后的结果为:");OutPrint(result, a, b); //输出结果}}public double[,] ZhuanZhi(double[,] x, int a, int b) //实现转置并且输出结果{double[,] y = new double[b, a]; //用于存放转置后的结果for (int i = 0; i < a; i++)for (int j = 0; j < b; j++)y[j, i] = x[i, j]; //第a行b列与第b行a列交换,实现转置Console.WriteLine("矩阵转置后的结果为:");OutPrint(y, b, a); //打印结果return y;}public void Time(double[,] x, int a, int b, double[,] y, int c, int d){double[,] result = new double[a, d]; //用来存放矩阵相乘后的结果if(b != c) //判断是否能够进行矩阵的乘法运算Console.WriteLine("x和y数组的位数不匹配,不能进行乘法运算");else{for (int i = 0; i < a; i++)for (int j = 0; j < d; j++){result[i, j] = 0;for (int k = 0; k < b; k++)result[i, j] += (x[i, k]) * (y[k, j]); //得到相乘后的每一项}Console.WriteLine("矩阵相乘后的结果为:");OutPrint(result, a, d); //打印结果}}public void QiuNi(double[,] x, int a, int b) //实现矩阵的求逆运算,并输出结果{double[,] result1 = new double[a, b]; //用来存放代数余子式矩阵double[,] result2 = new double[a, b]; //用来存放求逆后的矩阵if (a != b)Console.WriteLine("输入的行和列大小不相等,不能求逆矩阵");else{double m;m = QiuZhi(x, a); //求出行列式的模长,进行下一步的判断if (m == 0) //判断是否有逆矩阵Console.WriteLine("输入矩阵的模长值为0,所以它没有逆矩阵");else{result1 = QiuYuZiShi(x, a); //代数余子式double n = 1 / m;for (int i = 0; i < a; i++) //一一求出逆矩阵的每一项for (int j = 0; j < a; j++)result2[i, j] = n * result1[i, j];}}Console.WriteLine("矩阵求逆后的结果为:");OutPrint(result2, a, a);}}class Program{static void Main(string[] args){double[,] arr1;double[,] arr2;JuZhen p = new JuZhen(); //申明一个JuZhen类的一个实例JuZhen p1 = new JuZhen(); //给出即将输入的矩阵实例int x1, y1;JuZhen p2 = new JuZhen();int x2, y2;Console.WriteLine("请输入第一个矩阵的行"); //第一个矩阵的输入和输出x1 = int.Parse(Console.ReadLine());Console.WriteLine("请输入第一个矩阵的列");y1 = int.Parse(Console.ReadLine());Console.WriteLine("矩阵的行数为:{0},矩阵的列数为:{1}", x1, y1);arr1 = new double[x1, y1];arr1 = p1.InputArr(x1, y1);Console.WriteLine("选择1继续输入第二个矩阵,您将做***加法+++乘法****\n按其他数字做矩阵的***求逆+++转置***求行列式的值**选项");int n; //对矩阵运算的第一次选择n = int.Parse(Console.ReadLine());if (n == 1){Console.WriteLine("请输入第二个矩阵的行和列"); //第二个矩阵的输入和输出x2 = int.Parse(Console.ReadLine());y2 = int.Parse(Console.ReadLine());Console.WriteLine("矩阵的行数为:{0},矩阵的列数为:{1}", x2, y2);arr2 = new double[x2, y2];arr2 = p2.InputArr(x2, y2);Console.WriteLine("输入1做+++加法+++.输入2做***乘法***");int m;m = int.Parse(Console.ReadLine());switch (m){case 1: p.Add(arr1, x1, y1, arr2, x2, y2); break;case 2: p.Time(arr1, x1, y1, arr2, x2, y2); break;default: break;}}else{int a;Console.WriteLine("输入1做+++求逆法+++.输入2做+++转置***输入3做求行列式的值**");a = int.Parse(Console.ReadLine());switch (a){case 1: p.QiuNi(arr1, x1, y1); break;case 2: p.ZhuanZhi(arr1, x1, y1); break;case 3:if (x1 == y1)Console.WriteLine("行列式的值为:{0}", p.QiuZhi(arr1, x1));elseConsole.WriteLine("这不是行列式,因为行与列不相等,请重新启动程序");break;default: break;}}Console.WriteLine("按回车键退出");Console.Read();}}}。