-3

I'm writing a program where the user inputs the time interval and current position of a moving object and the program calculates the velocity of the object. It's in a loop so this segment will repeat continually asking the user for the next position of the object. The problem is I also need to keep track of the total velocity of the object. Usually I would store it in a variable, but I can't do that because you get the velocity from the program, not from user input.

Is there any way for me to store the velocity in a variable once the program calculates it?

cout<<"\nAverage Velocity (this interval):"<<(float)current_position/(float)time_interval<<" feet/second";

The result of THAT equation is what I want to store in a variable. How do I do it? When I do it with >>cin the program expects me to input a value for the total velocity which is NOT what I want.

This is my first post here so I'm sorry in advance if I broke any forum conventions. Thanks for the help!

  • 1
    `auto some_variable_name = (float)current_position/(float)time_interval;` - this is explained in any [good beginners C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), I suggest you read a few. – Jesper Juhl Oct 10 '22 at 03:45
  • @JesperJuhl How do I use that in my program? I declared my totalvelocity variable like you said and when I try to print it out I get "nan". The book my professor gave us doesn't explain how declaring a variable with auto will help with my problem. – rookie2344 Oct 10 '22 at 04:15
  • This likely means that `time_interval` is zero. NaN stand for "not a number", and is the vaue likely originating from a division by zero. – Igor Tandetnik Oct 10 '22 at 04:29
  • The time interval I input is 2, not zero. – rookie2344 Oct 10 '22 at 04:30
  • Did you put that line _before_ or _after_ reading the values of `current_position` and `time_interval`? C++ is not a spreadsheet. It sets the value of `some_variable_name` based on the current values of `current_position` and `time_interval`. If those variables get changed later, it doesn't go back and update the value of `some_variable_name`. – Nathan Pierson Oct 10 '22 at 06:26

1 Answers1

0

You need to identify your variables before using them and while you are identifying them you can give them a value Ex:

float velocity = 1;

instead of 1 you put the value of choice and you can use the "velocity" variable as you like. I hope I helped you out. Edit: Also there is no need to \n after the cout because when you type cout in a new line after the endl; it will automatically start a new line