Simple C++ calculation giving odd outputs [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm working on a C++ program to calculate a speeding ticket fine for different speeds.
"The speeding ticket fine policy in (City) is $50 plus $5 for each mph over the limit plus a penalty of $250 for any speed over 85 mph. Write a program that accepts a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of the fine, if the speed is illegal.In the program, you also need to display whether the number of miles over the speed limit, and if he/she is driving over 85 mph."
Here's my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double speedlimit,clockedspeed,speeddifference,fineunder85,fineover85;
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
cout<<"Enter the speed limit: "<<endl;
cin>>speedlimit;
cout<<"Enter the clocked speed: "<<endl;
cin>>clockedspeed;
if ((clockedspeed > speedlimit) && (clockedspeed > 85))
{
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: Yes"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineover85<<endl;
}
else {
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: No"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineunder85<<endl;
}
}
I'm getting weird outputs for (speeddifference) like "-7e-310" and the fine isn't adding the additional penalty ($5/mile over the limit) but is only outputting "$50" or "$300".
Just looking for help, I've searched everywhere and I've come up short.
ty all

You're calculating the speed difference and fines before you even input the numbers! Remember that the program runs line by line (without functions, classes, etc. just procedural programming). Furthermore, you declare the variables without defining them with a set value which is why you are getting random values.
Move the:
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
to after you receive input.
Edit:
There seems to be numerous other errors and I've tried my best effort to fix all of them. Here's a reworked version.
#include <iostream>
int main()
{
double fine = 0;
double speed_limit;
double clocked_speed;
std::string over_85 = "no";
std::cout << "Speed limit:\n";
std::cin >> speed_limit;
std::cout << "Clocked speed:\n";
std::cin >> clocked_speed;
double speed_difference = clocked_speed - speed_limit;
fine += 50 + speed_difference * 5;
if (clocked_speed > 85) {
fine += 250;
over_85 = "yes";
}
if (clocked_speed <= speed_limit) {
std::cout << "\nLegal\n";
}
else {
std::cout << "\nIllegal\n"
<< "Miles over: " << speed_difference << '\n'
<< "Over 85mph: " << over_85 << '\n'
<< "Fine: $" << fine << '\n';
}
}
Changes:
Set a variable string over_85; to remove need of complicated if statement.
Remove need for two different fines and instead have one fine with an if statement to add the $250 fine if necessary.

Related

Why is the int function acting strange when I set it to 500? c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I am trying to set a int to 500, but random numbers such as 22067 come out.
I am trying to make a simple gambling game. Currently, what I'm doing is that I set int gambledMoney = 500; But when I ask to print the 500, it does work but instead it prints 22067. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//introduction
cout << "Why hello human!\nWelcome to this gambling game where you... gamble!\nTo explain how to play here are the steps:\n\n";
//instructuions
cout << "You always start with $2000.\nAt the very beginning of each new round, you will be given choices on the amount of money you will gamble.\n";
cout << "Then you will gamble against an AI.\nIf you win, you gain the amount that the AI gambled...\nBut if you lose, you lose the money that you gambled.\n";
cout << "If you reach $500, you lose. Same goes with the AI.\n";
//game start
cout << "\nNow lets start!\n";
//gamble amount
string gambleChoice;
int gambledMoney;
cout << "\nHow much would you like to gamble?";
cout << "\n A) $500\n B) $750\n C) $1000\n D) $1250\n E) $1500\n F) $1750\n G) $2000\n\n";
//amount chosen
cin >> gambleChoice;
if (gambleChoice == "a")
{
int gambledMoney = 500;
}
cout << "\nYou have gambled $" << gambledMoney << "!" << endl;
return 0;
}
Does anyone know why it is not putting 500?
You are declaring two different variables with the name gambledMoney in different scopes, so that one variable "shadows" the other variable with the same name.
The line
int gambledMoney = 500;
will create a new variable with that name, and set it to 500. It won't change the value of the existing variable to 500.
You probably want to change that line to the following:
gambledMoney = 500;
That way, it will change the value of the existing variable, instead of creating a new one.
If you are using the compilers gcc or clang, I recommend that you compile with the -Wshadow command-line option. That way, the compiler will warn you when you create two variables of the same name, so that one shadows the other.
That is not the only compiler warning that I recommend enabling, though. You may want to read this for further information:
Why should I always enable compiler warnings?

For loop displaying incorrect information stored inside array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have this really simple program, with a for loop designed to run 3 times.
For every iteration, it will ask the user to enter in the weather. Each time, the user's input is stored in an integer array called C.
Once the loop concludes, I have another for loop that print's out the user's input. This next loop works fine for the 2 values, but gives off some weird messed up value once it reaches the third iteration.
int main(){
//Variable declaration:
int days;
int C[2];
int F[2];
for(days=0; days<3; days++){
cout << "What is the temperature in celsius for day " << days + 1 << ":" << endl;
cin >> C[days];
F[days] = (C[days] * 9/5) + 32;
}
cout << "\nCelsius\t\t Farenheit\n-------\t\t ---------" << endl;
for(days =0; days <3; days++){
cout << C[days] << "\t\t " << F[days] << endl;
}
return 0;
}
This next loop works fine for the 2 values but gives off some weird messed up value once it reaches the third iteration.
Your definition of C states it has 2 entries, but your loop runs for
three iterations (0, 1, and 2).

From the user's input total the odd and even numbers. input numbers in between 0 to 99 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int i,t,x[20], even, odd, prime;
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i];
}
cout << "\nPrime numbers are: " << endl ;
prime=1;
for (i=2; i<=20 ; i++)
{
for(t=2;t<x[i];t++)
{
if(x[i]%t==0)
{
prime=0;
}
}
if(prime==1)
{
cout << x[i] << endl;
}
prime=1;
}
for(i=1; i<=20; i++) // this is where i have problem.
{
if(x[i]% 2 == 0)
{
even++;
}
else
{
odd++;
}
}
cout << "Number of odd numbers: " << odd << "\n";
cout << "Number of even numbers: " << even << "\n";
return 0 ;
}
When i compile it shows even (40) and odd (10) for input of 0 till 19. Where it should show even 10(including the 0) and odd (10). Im not sure where am i doing it wrongly. I hope someone can help me improve the code.
Variables even and odd are never set to a known value, so you are not formally allowed to read from them. Doing so invokes that most infamous Standardese concept: undefined behaviour. So the values of these variables could be right or could be wrong; the variables and all code trying to read them could be optimised entirely out of your program; or anything can happen. You cannot rely on these variables doing anything right. All attempts to read them make your program ill-formed, so now it can do anything, including things you would never have imagined.
You should search for the abundant background info about these concepts, but I like to think I made a fairly decent summary here: https://stackoverflow.com/a/38150162/2757035
Also, as Thomas points out in the comments, you appear not to understand how array indexing works: Indexes are 0-based. So, int i[20] declares 20 elements numbered from 0 to 19. You try to access index 20, which is not part of the array and hence is more undefined behaviour.

Program crashes sometimes when dynamically allocating memory [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am learning about pointers and dynamically allocating memory. So my question I guess is more of a technical issue. Whenever it seems I use the 'new' keyword to allocate memory for whatever I am doing, my program will sometimes crash. Sometimes not.
#include <iostream>
#include <iomanip>
#include <cstdlib> //I added this header file to get the NULL, this is not originally from the book
using namespace std;
int main(){
double *salesArry = NULL;
double total = 0.0, average;
int numDays, count;
cout << "How many days of sales figured do you wish to process ";
cin >> numDays;
salesArry = new double[numDays];
cout << "Enter the sales figures below.\n";
for(count = 0; count < numDays; count++){
cout << "Day " << (count + 1) << ": ";
cin >> salesArry[count];
}
for(count = 0; count < numDays; count++){
total += salesArry[count];
}
average = total/numDays;
cout << fixed << showpoint << setprecision(2);
cout << "\n\nTotal Sales: $" << total << endl;
cout << "\n\nAverage Sales: $" << average << endl;
delete [] salesArry;
salesArry = NULL;
return 0;
}
Full disclaimer: I am a student, this is NOT homework. I posted a book example. I copied it word for word and still my program crashes. My only reason for posting code is someone will proably ask "Can we see the code". Now the project I was working on is doing the same thing (crashes) so I doubt that both the book and I are wrong so that is why I'm guessing its a technical issue. The IDE I am using is Dev C++ and its the default compiler.
This is from Tony Gaddis's book "Starting Out with C++" Chapter 9, page 524
new double(numDays);
Whoops! When you transcribed the book, you made a typographical error. (I can confirm that the 8th Edition, which you said you're using, does not make this mistake (figure 9-14, et al.).
To dynamically allocate an array, you must use square brackets, otherwise you're just initialising one dynamically-allocated double with the value numDays.
new double[numDays];
salesArry = new double(numDays);
That line doesn't create an array of numDays doubles, it allocates a single double and initializes it to numDays.
To create an array, you would use:
salesArry = new double[numDays];
In C++, however, it is preferable to use std::vector instead of dynamically allocating arrays by hand:
std::vector<double> salesArray (numDays);

Simple C++ Unit Conversion [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to create a beginner-level program that converts input from one unit of time to another. Essentially what I'm after is this: the user inputs a number of days, hours, and minutes, and those values get converted to both weeks and seconds. Here is what I have so far, which displays "0" for both weeks and seconds no matter the input.
EDIT: Fixed multiplication, new code for weeks. Still a garbage value.
#include <iostream>
using namespace std;
int main()
{
int days, hours, minutes, weeks, seconds;
cout << "--------------------" << endl;
cout << "Enter a number of days: ";
cin >> days;
cout << "Enter a number of hours: ";
cin >> hours;
cout << "Enter a number of minutes: ";
cin >> minutes;
seconds = (days*86400)+(hours*3600)+(minutes*60);
weeks = seconds/604800;
cout << "--------------------" << endl;
cout << "Equal to " << seconds << " seconds" << endl;
cout << "Equal to " << weeks << " weeks" << endl;
return 0;
}
I'm sure there is something I'm doing wrong in the conversion part. Any help is much appreciated, thank you.
All of your variables are ints, but you are performing very large divisions on them. When an int is divided into a non-whole number, the decimal is dropped rather than rounded (so 3/2 = 1, for example). The simplest way to fix this is to turn all your variables into doubles and possibly round them to two digits of precision using setprecision on cout. Alternatively, look into std::round
Weeks is int and also all the elements of your division, this implies in an integer division. To get the proper result, you should make weeks float and convert one of the operands BEFORE the division, like:
float weeks = float(seconds) / 604800;
or
float weeks = seconds / 604800.0;
I strongly disencourage the second way because makes code more difficult to read.