I am having trouble with the following line of code:
double answer;
answer = num[count] / den[count]
cout << " Fraction" << count + 1 << " " << num[count]
<< " / " << den[count] << " = " << answer << endl;
How come my rendition of answer is not working? Am I overlooking something? I am using arrays and am getting the data from a separate text file. When I use the code above I get the numbers that are to be divided correctly but the answer is incorrect. It comes out to be a random number usually 0 or 1.
Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int num[], int den[], int size);
void showValues(int num[],int den[], int size);
int main()
{
const int size1 = 12;
const int size2 = 12;
ifstream dataIn;
int num[12];
int den[12];
read_data(num,den,size1);
cout << "Here are the fractions: " << endl;
showValues(num,den,size1);
system("PAUSE");
return 0;
}
void read_data(int num[], int den[], int size)
{
ifstream dataIn;
dataIn.open("walrus.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
dataIn.close();
}
void showValues(int num[],int den[], int size)
{
int count;
for (count = 0; count < size; count++)
{
if (den[count] == 0)
{
cout << " Fraction" << count + 1 << " "
<< num[count] << " /" << den[count]
<< " Is invalid" << endl;
}
else
{
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
}
}
}
#main ifstream dataIn;
You are not using this object
#function read_data :
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> num[count];
}
for (count = 0; count < size; count++)
{
dataIn >> den[count];
}
Assuming ur file looks like :
1 2 23 32 44 // numerators
2 3 1 99 24 // den
The proper way to read is :
int count = 0;
while( count < size && dataIn >> num[count++] ) // numerators
;
count = 0;
while( count < size && dataIn >> den[count++] )
;
#function showValues :
try changing
double answer;
answer = num[count] / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count]
<< " = " << answer << endl;
to :
double answer = static_cast<double>(num[count]) / den[count];
cout << " Fraction" << count + 1 << " "
<< num[count] << " / " << den[count] << " = " << answer << endl;
In C and C++, if you do,
double answer = 10 / 3;
your answer will be 3. The reason is you have 2 integers and an integer division will take place. The resulting output is then implicitly converted into a double. So the steps are,
double answer = 10 / 3
double answer = 3
double answer = 3.0
To fix this, you tell the compiler that you want this to be treated as floating point division.
double answer = 10.0 / 3;
This works by,
double answer = 10.0 / 3
double answer = 10.0 / 3.0
double answer = 3.33333333...
The compiler will implicitly cast the 3 into a larger double type, 3.0.
So in your code, you have to convert integer division into floating point division by casting at least one of the division arguments into a double.
double foo = num[count] / den[count];
simply becomes
double foo = num[count] / static_cast<double>(den[count]);
Alternatively, if one or both of the arrays were of double type, you would not have this problem requiring casts.
Related
I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n = 0;
int sum = 0, total = 0;
fstream file("numbers.txt");
while (file >> n)
{
sum += n;
total++;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
int Highest;
int Negative;
cout << "Total result: " << sum << endl;
cout << "Numbers added: " << AmountOfNumbersAdded << endl;
cout << "Average number: " << average << endl;
cout << "Maxiumum number: " << endl;
cout << "Negative numbers: " << endl;
return 0;
}
i tried to do
float Highest = INT_MIN;
if (Highest < num[i]) {
Highest = num[i];
but it just wouldn't work.
You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
Negative += 1;
}
if (n > Highest)
{
Highest = n;
}
}
float average = (float)sum / total;
Here's what you're looking for.
#include <iostream>
#include <fstream>
int main()
{
int n = 0;
int sum = 0, total = 0;
int highest = 0;
int negatives = 0;
std::fstream file("numbers.txt");
while (file >> n)
{
if (n > highest) highest = n;
if (n < 0) ++negatives;
sum += n;
++total;
}
int average = (float)sum / total;
int AmountOfNumbersAdded = total;
std::cout << "Total result: " << sum << "\n";
std::cout << "Numbers added: " << AmountOfNumbersAdded << "\n";
std::cout << "Average number: " << average << "\n";
std::cout << "Maxiumum number: " << highest << "\n";
std::cout << "Negative numbers: " << negatives << "\n";
file.close();
return 0;
}
As you're new, few advices for you:
Never use using namespace std.
Prefer using "\n" instead of std::endl.
Don't forget to close any files/database after opening them like you did in your code.
Always try to avoid macros.
For some reason the values in the loop do not update. Instead of taking the new values they are assigned in the loop they stay the same as when first assigned. Why is this?
using namespace std;
int main() {
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
cout << "Enter the polulation of town A and of town B:" << endl;
cin >> town_A_Pop >> town_B_Pop;
cout << "Enter the growth rate of town A and of town B:" << endl;
cin >> town_A_Growth >> town_B_Growth;
do {
town_A_Pop = town_A_Pop * (1 + (town_A_Growth / 100));
cout << town_A_Pop << endl;
town_B_Pop = town_B_Pop * (1 + (town_B_Growth / 100));
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
cout << "It took " << years << " years for Town A to overtake Town B." << endl;
cout << "Town A Population: " << town_A_Pop << endl;
cout << "Town B Population: " << town_B_Pop << endl;
return 0;
}
I assume that town_A_Pop and town_B_Pop don't update.
If town_A_Growth is less than 100(and greater or same than 0) then (town_A_Growth / 100) will evaluate to 0 and (1 + (town_A_Growth / 100)) will evaluate to 1.
In that case, town_A_Pop = town_A_Pop * 1 so it will stay same.
Same goes to town_B_Pop.
To fix the problem, you can change variables into float or double, or multiply first then divide by 100 like below:
do {
town_A_Pop = (town_A_Pop * (100 + town_A_Growth)) / 100;
cout << town_A_Pop << endl;
town_B_Pop = (town_B_Pop * (100 + town_B_Growth)) / 100;
cout << town_B_Pop << endl;
years++;
}
while (town_A_Pop < town_B_pop);
It will still won't get bigger if both population and growth are too small, though.
Your problem is Type Variables Error
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
change to
double town_A_Pop;
double town_A_Growth;
double town_B_Pop;
double town_B_Growth;
double years;
This should be ok. Because if using int to do division it not able return decimal number.
Like:
int tmp = 1;
int division = tmp / 5; //This result will return 0 , not return 0.2
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
I'm currently working on a program that outputs the number 1089 (i.e the Magic Number) of a three digit integer who's first digit is greater than its last. I have some code typed up, but am not receiving 1089, instead I'm receiving 891. Could anyone offer some explanation as to why.
//Uses a cout to inform user will be using the number 412 as an example.
//Uses a cout to explain to user the number needs to be reversed.
cout << "Alright, let's walk through an example, using the number 412." << endl;
int numExample = 412;
cout << "Please input 412" << endl;
cin >> numExample;
cout << "First, the number 412 is reversed." << endl;
//The following is done for reversing the number 412:
int reverseNum = 0, remainder = 0;
while (numExample)
{
remainder = numExample % 10;
reverseNum = (reverseNum * 10) + remainder;
numExample = numExample / 10;
}
cout << "The reverse of 412 is " << reverseNum << endl;
cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl;
cout << "This gives us 198" << endl;
cout << "From there, we want to reverse 198." << endl;
//The same procedure is used to reverse 198
int numExample2 = 198;
cout << "Please enter 198" << endl;
cin >> numExample2;
int reverseNum2 = 0, remainder2 = 0;
while (numExample2)
{
remainder2 = numExample2 % 10;
reverseNum2 = (reverseNum2 * 10) + remainder2;
numExample2 = numExample2 / 10;
}
cout << "The reverse of 198 is " << reverseNum2 << endl;
int magicNumber = (reverseNum2 + numExample2);
cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl;
Try writing a function to handle this so your code is cleaner (It will also make it easier for people to help you!)
#include <iostream>
#include <cmath>
using namespace std;
int reverseDigit(int num); // For example purposes
int _tmain(int argc, _TCHAR* argv[])
{
int Number1,
Number2,
temp1,
temp2,
Result;
cout << "Enter the number 412: ";
cin >> Number1;
temp1 = reverseDigit(Number1);
temp1 = Number1 - temp1;
cout << "Enter the number 198: ";
cin >> Number2;
temp2 = reverseDigit(Number2);
Result = temp1 + temp2;
cout << "The magic number is: " << Result << endl;
return 0;
}
int reverseDigit(int num)
{
int reverseNum = 0;
bool isNegative = false;
if (num < 0)
{
num = -num;
isNegative = true;
}
while (num > 0)
{
reverseNum = reverseNum * 10 + num % 10;
num = num / 10;
}
if (isNegative)
{
reverseNum = -reverseNum;
}
return reverseNum;
}
I realize you're not working with negatives so you can remove that bit if you chose to use this, you can also expand on it... That being said this will make the actual " Reversing process " easier to work with and improve upon and read.
I am having some trouble in my marked "Median" function. I am getting an error that says `Horse[10][double]' for array subscript. I am not sure how to fix this and I am looking for some friendly help.
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Horses2
Author: Grant Birkinbine
Date: 03/12/14 18:25
Description: A program that modifies the Horses program
*/
//Start
using namespace std;
//Class
class Horse{
private:
string name ;
int lane;
double time;
public:
Horse(string hname , int hlane , double htime){
name = hname ;
lane = hlane ;
time = htime;
}
Horse(){
name = "" ;
lane = 0 ;
time = 0 ;
}
void setname(string hname){
name = hname;
}
void setlane(int hlane){
lane = hlane;
}
void settime(double htime){
time = htime;
}
string getname (){
return name ;
}
int getlane(){
return lane;
}
double gettime(){
return time;
}
void print(){
cout << "Horse Name: " << name << endl;
cout << "Horse Lane: " << lane << endl;
cout << "Horse Time: " << time << endl;
cout << endl;
}
};
//Main
void insertion_sort(Horse x[],int length);
int main(int argc, char *argv[])
{
cout << "Horse Race Results: " << endl << endl;
Horse ahorse[10];
ahorse[0] = Horse("American idol " , 1 , 45.41);
ahorse[1] = Horse("Bababooey " , 2 , 42.42);
ahorse[2] = Horse("Charlie Horse " , 3 , 40.94);
ahorse[3] = Horse("Dog Biscuit " , 4 , 43.55);
ahorse[4] = Horse("Echo " , 5 , 41.41);
ahorse[5] = Horse("Firefox " , 6 , 42.58);
ahorse[6] = Horse("Google " , 7 , 42.58);
ahorse[7] = Horse("Hoof-Hearted " , 8 , 44.57);
ahorse[8] = Horse("Ima Loozer " , 9 , 41.57);
ahorse[9] = Horse("Just Walking " , 10 , 50.00);
//Sorting
int length = 10;
insertion_sort(ahorse, length);
double avg;
double x;
double max;
double min;
avg=0;
x = 0;
int abovea = 4 ;
int belowa = 6 ;
int abovem = 4 ;
int belowm = 4 ;
//Average
for (int i =0 ; i<10 ; i++ ) {
x = x + ahorse[i].gettime() ;
}
avg = (x / 10);
//Max
for(int i = 0 ; i < 10 ; i++){
max = -1000;
if ( ahorse[i].gettime() > max){
max = ahorse[i].gettime();
}
}
//Min
for(int i = 0 ; i < 10; i ++){
min = 1000;
if ( ahorse[i].gettime() < min){
min = ahorse[1].gettime() ;
}
}
for(int i = 0; i < 10; i++){
ahorse[i].print() ;
}
//Median
double median;
if(ahorse[x].gettime() % 2 == 0){
median = (ahorse[10].gettime() / 2) + (ahorse[10].gettime() / 2 + 1) / 2;
}
else{
median = (ahorse[10].gettime() / 2) + 1;
}
cout << "Average: " << avg << endl;
cout << "Fastest Time: " << min << endl;
cout << "Slowest Time: " << max << endl;
cout << "# Above Mean: " << abovea << endl;
cout << "# Below mean: " << belowa << endl;
cout << "# Above median: " << abovem << endl;
cout << "# Below median: " << belowm << endl;
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
void insertion_sort(Horse x[],int length){
Horse key;
int i;
for(int j=1;j<length;j++)
{
key= x[j];
i=j-1;
while(x[i].gettime()>key.gettime() && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}
First, you can't use a double to subscript an array, soahorse[x].gettime()won't work, arrays has to be subscripted using integers. Think about it, what element wouldahorse[9.5]refer to?
Second, the modulus operator%only works for integers. Use fmod if you want to do mod on double
Third, arrays are indexed starting from zero, so the access toahorse[10]in the median part is accessing the array outside it's bound and is an invalid memory access as the last element of theHorse ahorse[10]array isahorse[9].
There might be other issues, but the ones mentioned above are the ones I spotted at a first glance.