Trouble with my first program

closed account (98U9GNh0)
I am making a Reimann sum calculator for my first "real" program (that is other than hello world and such)

It is currently unfinished since i still have to learn how to do loops. I am not requesting help on how to do loops, I will learn that myself as I get further into the tutorial I'm using.

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "stdafx.h"
#include <iostream>

	float a; // start
	float b; // end
    int n; // partitions
    float y; // function
	float x; // x value
	float z; // current partition area
	float w; // partition area sums
	float l; // loop number

void loopn()
{
	
	l = l+1;
}
 

int main()
{
	using namespace std;
    
	w = 0 ;
	l = -1; //for right side aproximation, make l = 0
	
	cout << "This program aproximates the definite integral of a function with the Riemann sums of n partitions of an interval in the funcion." << endl;
	cout << "Define a funtion of x"  << endl;
	cout << "f(x)= " ;
    cin  >> y;
	cout << "Start?"   << endl;
	cin  >> a;
	cout << "End?"     << endl;
	cin  >> b;
	cout << "n?"       << endl;
	cin  >> n;
    
	
	
    
		                       // this needs to be looped n - 1 times
loopn();                       
	                          
    x = a + l * (b - a )/n;        
    	                      
	z = y * (b - a)/n;
	
	w = w + z;                // loop ends here
	
	cout << w << endl;
	return 0;
}


The program compiles correctly, and It works well when i input numerical values for y, but when i try to input a mathematical expression such as x, x + 2, x *2, or anything of the sort, the program behaves weirdly. It will skip asking me for a, b, and n and the program will close without outputting the result.

Any idea what I'm doing wrong?

You defined y to be a single floating point value.

If you input something that is not a floating point value (or cannot be implicitly converted to a floating point value), such as x, x + 2, x *2, or anything of the sort, it will all go wrong.
Last edited on
closed account (98U9GNh0)
I though since x was defined as a float value, any operation on x would result in a float value as well. I guess that's not how it works.

How do I define y to be able to handle mathematical functions?
Expression parsers are not trivial.

http://www.cplusplus.com/forum/beginner/6132/
closed account (98U9GNh0)
Ill postpone my program then, for when I'm a bit more advanced, thanks for your help folks.
Topic archived. No new replies allowed.