BinaryArt 10 發表於 September 29, 2008 檢舉 Share 發表於 September 29, 2008 如題 我剛開始自學C++,用的是dev 想先寫個解二次方程式的程式我寫的如下:問題在他無法接受 (-b+(b^2+4*a*c)^0.5)/2*a 裡的 ^ (次方) 運算 x^y x,y為小數時會顯試錯誤; "^" 運算結果也不正確 (我測試2^3 結果為1)---------------------------------------------------------------------------------------------------------------#include <iostream>#include <math.h>#include <stdlib.h>using namespace std;int main(){ int a; int b; int c; int d; int e; cout << "此為解二次方程式程式!\n" << endl; cout << "請輸入二次項係數:"; cin >> a; cout << "您輸入的二次項係數為:" << a <<"\n"<< endl; cout << "請輸入一次項係數:"; cin >> b; cout << "您輸入的一次項係數為:" << b <<"\n"<< endl; cout << "請輸入常數項:"; cin >> c; cout << "您輸入的常數項為:" << c <<"\n"<< endl; d=(-b+(b^2+4*a*c)^0.5)/2*a; e=(-b-(b^2+4*a*c)^0.5)/2*a; cout << "您輸入的二次方程式之二根分別為:" << d << "," << e << endl; system("pause") ; return 0;}-----------------------------------------------------------------------------------------------------------------------我知道這個遇到非有理數或非實數解時會有問題 我只是想先試試看簡單的麻煩各位高手指點! 是哪裡出錯了呢? 或是有更好的寫法嗎? 鏈接文章 分享到其他網站
楊少女 10 發表於 October 5, 2008 檢舉 Share 發表於 October 5, 2008 該輸入的公式是[-b+(b^2-4*a*c)^1/2]/2*a或[-b-(b^2-4*a*c)^1/2]/2*a吧根號裡面放的咚咚是「減」4ac喔= ="" 鏈接文章 分享到其他網站
j100002ben 10 發表於 October 5, 2008 檢舉 Share 發表於 October 5, 2008 二次方就直接b*b解決比較快....不過要小心溢位的問題....如果要用次方功能的話.... yx我們可以這樣寫....x,y是double型態的...#.....#include <math.h>int main(void){....double ans;....ans = pow(x,y);....}或是自己寫一個也可以啊....正整數次方的....long mypow(long x,long y){long s,i;for(i=0,s=1;i<y;i++) s*=x;return s;} 鏈接文章 分享到其他網站
john0312 10 發表於 October 6, 2008 檢舉 Share 發表於 October 6, 2008 C 裡面, "^" 指的是xor運算,不是n次方. 要n次方, 請用: (溢出自行防範... 結果不可超過2^31)long RaiseToNthPower( long base, long exponent ){ long result = 1; // 1 is base to the power of 0 for ( long i = 0; i < exponent; i++ ) result = result * base; } return result;};還有, 這種東西一般用float/double較為適當, 你的程式碼我做了一些修正.#include <iostream>#include <math.h>#include <stdlib.h>using namespace std;int main(){ float a; float b; float c; float d; float e; cout << "此為解二次方程式程式!\n" << endl; cout << "請輸入二次項係數:"; cin >> a; cout << "您輸入的二次項係數為:" << a <<"\n"<< endl; cout << "請輸入一次項係數:"; cin >> b; cout << "您輸入的一次項係數為:" << b <<"\n"<< endl; cout << "請輸入常數項:"; cin >> c; cout << "您輸入的常數項為:" << c <<"\n"<< endl; d=((-b)+sqrt(b*b-4*a*c))/(2*a); e=((-b)-sqrt(b*b-4*a*c))/(2*a); cout << "您輸入的二次方程式之二根分別為:" << d << "," << e << endl; system("pause"); return 0;} 鏈接文章 分享到其他網站
taichunmin 10 發表於 December 26, 2008 檢舉 Share 發表於 December 26, 2008 還有一個功用比較狹隘的函式叫sqrt()需含括<cmath>他的功用只是開根號參數只允許放浮點數喔 鏈接文章 分享到其他網站
j100002ben 10 發表於 December 28, 2008 檢舉 Share 發表於 December 28, 2008 事實上pow函數就可以用了.....double pow(double x,double y)次方轉成小數就可以開根號了..... 鏈接文章 分享到其他網站
TerryW 10 發表於 January 29, 2009 檢舉 Share 發表於 January 29, 2009 -b應該不可以吧可以考慮使用-1*b-b是可以的"-"同時也是一元運算子喔 鏈接文章 分享到其他網站
Recommended Posts
請登入後來留意見
在登入之後,您才能留意見
立即登入