2

## C++ for loop 不能動

precision我想要的準確率 當我輸入0.0001 它能顯示答案 但0.0000001時等多一個多小時也沒結果..

``````#include <iomanip>
#include <iostream>
using namespace std;
#include <math.h>
double precision;
double  xaxis;
double  yaxis;
unsigned long long int squares=0;
double powa;
double powb;

main(){

cout << "Please enter the precision: " << endl;
cin >> precision;
cout << "Please enter the width and height of the ellipse: " << endl;
cin >> xaxis >> yaxis;
powa = pow(xaxis,2);
powb = pow(yaxis,2);

double i;
for (i= precision / 2;i < xaxis ;i = i + precision){
double j;
for( j = precision / 2;j <= yaxis ;j = j + precision){
if(pow(i,2) / powa  + pow(j,2) / powb <= 1){
++squares;
}}}

long double area = 4.0*squares*precision*precision;
cout << setprecision(9) << area << endl;

return 0;

}
``````

lam814 iT邦新手 5 級 ‧ 2020-03-06 16:19:18 檢舉

fillano iT邦超人 1 級 ‧ 2020-03-06 18:27:19 檢舉

fillano iT邦超人 1 級 ‧ 2020-03-06 18:40:51 檢舉

lam814 iT邦新手 5 級 ‧ 2020-03-06 19:03:49 檢舉
0.0000001是作業的要求
http://www.opencoarrays.org/

froce iT邦大師 1 級 ‧ 2020-03-06 21:53:43 檢舉

### 2 個回答

0

iT邦大神 1 級 ‧ 2020-03-07 08:54:23

``````#include <iostream>
#include <math.h>

using namespace std;

double precision;
double  xaxis;
double  yaxis;
unsigned long long int squares=0;
unsigned long long int loopcnt=0;
double powa;
double powb;
double divi;

int main()
{
cout << "Please enter the precision: " << endl;
cin >> precision;
cout << "Please enter the width and height of the ellipse: " << endl;
cin >> xaxis >> yaxis;
powa = pow(xaxis,2);
powb = pow(yaxis,2);

double i, j;
for (i= precision / 2;i < xaxis ;i = i + precision){
divi = pow(i,2) / powa;
for( j = precision / 2;j <= yaxis ;j = j + precision) {
loopcnt++;
if ((divi  + (pow(j,2) / powb)) <= 1){
++squares;
}
else {
break;
}
}
}

long double area = 4.0*squares*precision*precision;
cout << "xaxis:" << xaxis << " yaxis:" << yaxis << " precision:" << precision << " area:" << area << endl;
cout << "Loopcnt:" << loopcnt << " squares:" << squares << " ratio:" << (double)squares/loopcnt << endl;

return 0;
}
``````

2
fillano
iT邦超人 1 級 ‧ 2020-03-07 20:19:51

``````//let preci = 0.00000001
let preci = 0.0001;
let a = 5;
let b = 3;
let sq = 0;
for(let y=0; y<b; y+=preci) {
for(let x=0; x<a; x+=preci) {
if(Math.pow(y,2)/Math.pow(b,2)+Math.pow(x,2)/Math.pow(a,2) <= 1) {
sq++;
}
}
}
console.log(4 * sq * Math.pow(preci,2));

sq = 0;
for(x=0; x<a; x+=preci) {
// x^2/a^2+y^2/b^2=1
// y^2=(1-x^2/a^2)*b^2
// y=sqrt((1-x^2/a^2)*b^2)
let y = Math.sqrt((1-Math.pow(x,2)/Math.pow(a,2))*Math.pow(b,2));
sq += y * preci;
}
console.log(sq*4);
``````
fillano iT邦超人 1 級 ‧ 2020-03-07 20:27:50 檢舉