日期:2014-05-16 浏览次数:21056 次
#include<gtk/gtk.h> #include<stdlib.h> #include<stdio.h> #include<malloc.h> #include<ctype.h> #include<string.h> struct cal { char h; char hh[30]; struct cal *next; }; char * operating(char ch[10]) { int i=0,j=0; char temp[20]; char *t; char *s; struct cal *head,*pre,*p; head=(struct cal *)malloc(sizeof(struct cal)); pre=head; p=head; p->next=NULL; while(ch[i]!='=') { j=0; p->next=(struct cal *)malloc(sizeof(struct cal)); p=p->next; p->next=NULL; p->h=ch[i++]; while(ch[i]!='+'&&ch[i]!='-'&&ch[i]!='*'&&ch[i]!='/'&&ch[i]!='=') { temp[j++]=ch[i++]; } temp[j]='\0'; strcpy(p->hh,temp); } pre=head; p=pre->next; if(p==NULL) return; pre=p; p=pre->next; while(p) { if(p->h=='*'||p->h=='/') { if(p->h=='*') { gcvt(atof(pre->hh)*atof(p->hh),10,s); strcpy(pre->hh,s); } else { gcvt(atof(pre->hh)/atof(p->hh),10,s); strcpy(pre->hh,s); } pre->next=p->next; free(p); p=pre->next; continue; } pre=p; p=pre->next; } pre=head; p=pre->next; if(p==NULL) { return; } pre=p; p=pre->next; while(p) { if(p->h=='+') { gcvt(atof(pre->hh)+atof(p->hh),10,s); strcpy(pre->hh,s); } else { gcvt(atof(pre->hh)-atof(p->hh),10,s); strcpy(pre->hh,s); } pre->next=p->next; free(p); p=pre->next; } printf("%s\n",pre->hh); /*显示结算结果在终端,*/ return pre->hh; /*返回计算结果*/ } void on_clicked(GtkWidget *button,gpointer date) /*这是事件函数,处理按钮事件的*/ { char temp[255]; char tempp[255]="+"; char *t="="; strcpy(temp,gtk_entry_get_text(GTK_ENTRY(date))); strcat(temp,gtk_button_get_label(GTK_BUTTON(button))); gtk_entry_set_text(GTK_ENTRY(date),temp); if(strcmp(gtk_button_get_label(GTK_BUTTON(button)),t)==0) /*当按下等于按钮时调用子函数,把字符串传过去,进行计算*/ { strcat(tempp,temp); /*在字符串前面加一个字符‘+’,此处不多加解释,在子函数里面需要用到*/ strcpy(temp,tempp); gtk_entry_set_text(GTK_ENTRY(date),operating(temp));/**返回计算结果,并显示在文本框中*/ } } void main(int a,char *b[]) /*主函数,负责创建计算器界面*/ { GtkWidget *window; GtkWidget *text; GtkWidget * button[16]; GtkWidget *table; GtkWidget *table2; int i=0,j=0,z=0; char temp[16][2]={{'0',0x00},{'1',0x00},{'2',0x00},{'3',0x00},{'4',0x00},{'5',0x00},{'6',0x00},{'7',0x00},{'8',0x00},{'9',0x00},{'.',0x00},{'=',0x00},{'+',0x00},{'-',0x00},{'*',0x00},{'/',0x00}}; gtk_init(NULL,NULL); window=gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window),"祥子之简易计算器"); table=gtk_table_new(2,1,FALSE); table2=gtk_table_new(4,4,FALSE); text=gtk_entry_new(); gtk_container_add(GTK_CONTAINER(window),table); gtk_table_attach(GTK_TABLE(table),text,0,1,0,1,(GtkAttachOptions)(GTK_FILL|GTK_EXPAND),(GtkAttachOptions)(0),0,0); gtk_table_attach(GTK_TABLE(table),table2,0,1,1,2,(GtkAttachOptions)(GTK_FILL),(GtkAttachOptions)(GTK_FILL|GTK_EXPAND),0,0); for(;i<16;j++,i++) { button[i]=gtk_button_new_with_label(temp[i]); if(j%4==0) { j=0;