生活随笔
收集整理的這篇文章主要介紹了
九度-题目1103 二次方程计算器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://ac.jobdu.com/problem.php?pid=1103
?
題目1103:二次方程計算器
時間限制:1 秒
內存限制:32 兆
特殊判題:否
提交:3767
解決:872
題目描述: 設計一個二次方程計算器
輸入: 每個案例是關于x的一個二次方程表達式,為了簡單,每個系數都是整數形式。
輸出: 每個案例輸出兩個實數(由小到大輸出,中間由空格隔開),保留兩位小數;如果無解,則輸出“No Solution”。
樣例輸入: x^2+x=3x+4 樣例輸出: -1.24 3.24 來源:2011年上海交通大學計算機研究生機試真題對字符串的遍歷判斷,判斷的條件比較多,要考慮到每一種可能的狀態。 1 #include <iostream>
2 #include <iomanip>
3 #include <math.h>
4 #include <ctype.h>
5 using namespace std;
6
7 void operate(string str,int &A,int &B,int &C){
8 for(int i=0;i<str.length();i++){///1
9 if(str[i] == '+')
10 continue;
11 else if(str[i] == '-'){///2
12 //不處理
13 }
14 else if(str[i] == 'x'){///3 //系數為正負1的情況
15 if(i+1 < str.length() && str[i+1] == '^'){
16 if(i-1>=0 && str[i-1] == '-')
17 A = A - 1;
18 else
19 A += 1;
20 i = i + 2;
21 }
22 else{
23 if(i-1>=0 && str[i-1] == '-')
24 B = B -1;
25 else
26 B += 1;
27 i = i + 1;
28 }
29 }
30 else{///4 是數字
31 int temp = 0;
32 int j = i;
33 while(isdigit(str[i])){
34 temp = temp*10 + str[i] - '0';
35 i++;
36 }
37 if(j-1>=0 && str[j-1] == '-')
38 temp = 0 - temp;
39 if(i< str.length() && str[i] == 'x'){
40 if(i+1 < str.length() && str[i+1] == '^'){
41 A += temp;
42 i = i + 2;
43 }
44 else{
45 B += temp;
46 i = i + 1;
47 }
48 }
49 else
50 C += temp;
51 }
52
53 }
54 }
55
56 int main(){
57 string str;
58 while(cin>>str){
59
60 int j = str.find('=', 0);
61 string str_left,str_right;
62 str_left = str.substr(0,j);
63 str_right = str.substr(j+1);
64 int A1 = 0,B1 = 0,C1 = 0;
65 int A2 = 0,B2 = 0,C2 = 0;
66 operate(str_left,A1,B1,C1);
67 operate(str_right,A2,B2,C2);
68 int a = A1 - A2;
69 int b = B1 - B2;
70 int c = C1 - C2; //化方程為標準式,a,b,c為系數
71 int temp = b*b - 4*a*c;
72 if(temp < 0)
73 cout<<"No Solution"<<endl;
74 else{
75 double x1,x2;
76 x1 = (double)(0-b+sqrt(temp))/(2*a);
77 x2 = (double)(0-b-sqrt(temp))/(2*a);
78 if(x1<x2)
79 cout<<fixed<<setprecision(2)<<x1<<" "<<x2<<endl;
80 else
81 cout<<fixed<<setprecision(2)<<x2<<" "<<x1<<endl;
82 }
83 }
84 return 0;
85 } ?
轉載于:https://www.cnblogs.com/shenckicc/p/6862359.html
總結
以上是生活随笔為你收集整理的九度-题目1103 二次方程计算器的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。