-1
#include <iostream>
#include <cmath>
using namespace std;
int main() {

int n = 5;
float area = 0.0;
float totalarea = 0.0;
float dx = 1.0/n;

float x = 0.0;


cout << "number of rectangles?:";
cin >> n;
for (int i=1; i<=n; i++){
    area = (1/n) * pow(1.0 - pow(x,2.0),0.5) ;

    totalarea += area;
    x = x + dx;
}
cout << totalarea << endl;

return 0;
}

I am trying to estimate the area of a quarter circle using rectangles. When I enter 1, I get 1 as the output. When I enter an integer 2-6 I get 0 as the output. When I enter an integer above 6, I get "not a number" as the output. Can someone help me fix my code.

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • 2
    You need to take the time to learn how to debug your own problems. It is an indispensable tool you should learn immediately. It will save you countless hours of just staring at your code wondering what is happening. – bolov Feb 27 '19 at 03:14
  • 3
    `1/n` is integer arithmetic and will result in `0` for any `i` other than `1`. You need `1.0 / n`. – bolov Feb 27 '19 at 03:15
  • Change this: `(1/n)` to this `(1./n)`. *(Understanding exactly why will go a long way towards your learning)* – abelenky Feb 27 '19 at 03:16
  • Possible duplicate of [Integer division always zero](https://stackoverflow.com/questions/9455271/integer-division-always-zero) – phuclv Feb 27 '19 at 03:29

1 Answers1

0

In addition to fixing the integer division issue as mentioned in the comments, you also need to hold off on setting dx until after you have the value of n.

#include <iostream>
#include <cmath>
using namespace std;
int main() {

    int n;
    float area = 0.0;
    float totalarea = 0.0;
    float dx;

    float x = 0.0;


    cout << "number of rectangles?:";
    cin >> n;
    dx = 1.0/n;
    for (int i=1; i<=n; i++){
        area = (1./n) * pow(1.0 - pow(x,2.0),0.5) ;

        totalarea += area;
        x = x + dx;
    }
    cout << totalarea << endl;

    return 0;
}
Gardener
  • 2,591
  • 1
  • 13
  • 22