Decimal point not displaying - c++

I intend to let user key in positive integer value only but I realized that the output is wrong. For example largest value I entered is 100.6, the largest value displayed is only 100. I believe the problems come from atoi. Can anyone look at my code and tell me whats wrong?
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int SIZE = 12;
string month[SIZE] = { "Jan", "Feb", "Mar","April","May","June","July","August","Sept","October","Nov","Dec"};
string highestMonth, lowestMonth;
char temp[SIZE];
double rainFall[SIZE], total = 0.0, average, highest, lowest;
bool flag;
int i = 0;
do{
flag = false;
cout << "Enter rainfall for " << month[i] << " : ";
cin >> temp;
for (int j = 0; j < strlen(temp); j++)
{
if (!isdigit(temp[j]))
{
if (temp[j] == '.')
continue;
cout << "Enter positive integer value only" << endl;
flag = true;
break;
}
}
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
} while (i < SIZE);
average = total / 12.0;
lowest = rainFall[0];
lowestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i] < lowest)
lowest = rainFall[i];
lowestMonth = rainFall[i];
}
highest = rainFall[0];
highestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i]>highest)
highest = rainFall[i];
highestMonth = rainFall[i];
}
cout << "Total rainfall:" << total << endl;
cout << "Average:" << average << endl;
cout << "Highest:" << highest << " in " << highestMonth << endl;
cout << "Lowest:" << lowest << " in " << lowestMonth << endl;
system("pause");
return 0;
}

atoi convert string representation of a number into an integer so "100.6" is converted into 100.
You can use atof

You set flag to true if the input has a decimal point and you have no code to process the decimal input whatsoever.
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
This code processes the input if flag is false, but there's no analogous code to handle decimals if flag is true.

Related

Failing to properly print multidimensional array column?

I recently have been having trouble with this simple problem, at the end of the code there are two blocks of text dedicated to finding the highest/lowest grade from what the user inputted.
That was simple enough and it works well, but I also need to print the a row corresponding to the lowest/highest graded student.
Essentially I'm working with the marks[5][4] array, the first array being the students, the second array being the exams.
If the lowest graded student was the student on array [2][] then I would I want to print out [2][i] using a for loop.
For the second array it works fine, the problem is I'm having problem on how to link the lowest graded student to the first array link.
I tried to use the count1 and count loops but they return a mess. I have been at this for a few hours and need a nudge in the right direction.
Thank you very much.
#include<iostream>
using namespace std;
int main()
{
char grade[5];
double avg[5];
string name[5];
int marks[5][4];
for (int i = 0; i < 5; i++) {
cout << "\n enter student" << i + 1 << "name :";
cin >> name[i];
cout << "\n enter four subject marks:";
for (int j = 0; j < 4; j++) {
cin >> marks[i][j];
}
}
for (int i = 0; i < 5; i++)
{
int sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + marks[i][j];
}
avg[i] = sum / 4;
if (avg[i] > 90.0 && avg[i] <= 100.0) {
grade[i] = 'A';
}
else if (avg[i] > 80.0 && avg[i] <= 90.0) {
grade[i] = 'B';
}
else if (avg[i] > 70.0 && avg[i] <= 80.0) {
grade[i] = 'C';
}
else if (avg[i] > 60.0 && avg[i] <= 70.0) {
grade[i] = 'D';
}
else if (avg[i] <= 60.0) {
grade[i] = 'F';
}
}
for (int i = 0; i < 5; i++)
{
cout << "\nName :" << name[i];
cout << "\tAverage : " << avg[i];
cout << "\tGrade : " << grade[i];
}
for (int i = 0; i < 4; i++)
{
int sum2 = 0;
for (int j = 0; j < 5; j++) {
sum2 = sum2 + marks[j][i];
}
cout << "\n";
cout << "The average of each exam " << i+1 << " is " << "%" << sum2 / 5;
}
//LOWEST
int count1;
int lowest;
lowest = avg[0];
for (count1 = 1; count1 < 5; count1++)
{
if (avg[count1] < lowest)
lowest = avg[count1];
}
cout << "\n";
cout << "The lowest average grade is is: " << lowest << ".\n";
for (int i = 0; i < 4; i++) {
cout << marks[count1][i] << " ";
}
cout << endl;
//Ends lowest.
//HIGHEST
int count;
int highest;
highest = avg[0];
for (count = 1; count < 5; count++)
{
if (avg[count] > highest)
highest = avg[count];
}
cout << "\n";
cout << "The highest average grade is is: " << highest << ".\n";
for (int i = 0; i < 4; i++) {
cout << marks[count][i] << " ";
}
cout << endl;
//Ends highest.
return 0;
}
From what I understand, you need to link the name with the lowest avg student
I recommend that instead of initializing lowest and highest with the average, initialize it with the index of the lowest and highest average. You can then compare the averages in the for loop like this
if (avg[lowest] >= avg[count1])
lowest = count1;
or you can follow Sam's solution, create another variable to store the index of the current lowest and highest avg

Trying to build menu in C++ that will take functions

I want the program to ask the user to enter a number and then that function in the array will display on the screen
e.g
case 0 = displayNums (displays numbers entered by the user)
case 2 = getAverage (gets average of numbers entered)
I tried to code the menu to do that, but it only shows up. Nothing happens when the number for the specific function is entered.
#include <iostream>
#define integer 12
int ShowMenu(void);
double displayNums(double[], int);
double GetTotal(double[], int);
double getAverage(double[], int);
double getLargest(double[], int, int*);
double getSmallest(double[], int, int*);
int getNumOccurence(double[], int, int n);
double scaleUp(double[], int);
using namespace std;
int main() {
cout << "enter 12 integers 1 by 1:\n";
int data;
int n = 1;
// array to hold the integers
double arr[integer];
// get the integers
for (int i = 0; i < 12; i++) {
cin >> arr[i];
}
int option;
do {
option = ShowMenu();
switch (option) {
case 0:
double displayNums();
break;
case 1:
double GetTotal();
break;
case 2:
double getAverage();
break;
case 3:
double getLargest();
break;
case 4:
double getSmallest();
break;
case 5:
int getNumOccurence();
break;
case 6:
double scaleUp();
break;
case 7:
break;
default:
cout << "invalid option\n";
}
} while (option != 7);
// displays numbers entered by user
cout << displayNums(arr, integer) << endl;
// displays sum of numbers entered
cout << GetTotal(arr, integer) << endl;
// displays the average
cout << "Average integer is:" << getAverage(arr, integer) << endl;
// displays the largest
cout << "Largest integer is: " << getLargest(arr, integer, &data) << endl;
// display the smallest integer
cout << "Smallest integer is:" << getSmallest(arr, integer, &data) << endl;
// display the occurence of the num
cout << "Occurence integer is:" << getNumOccurence(arr, integer, n) << endl;
// display the scale up integers
cout << "Scaled up integers are:" << scaleUp(arr, integer) << endl;
return 0;
}
int ShowMenu(void) {
int option;
cout << "\t0. Display Numbers\n";
cout << "\t1. Get Total of numbers\n";
cout << "\t2. Get Average\n";
cout << "\t3. Get Largest\n";
cout << "\t4. Get Smallest\n";
cout << "\t5. Get Number Occurences\n";
cout << "\t6. Scale Up\n";
cout << "\t7. Quit\n";
cout << "\t\t\tOption ? ";
cin >> option;
return option;
}
double displayNums(double arr[], int size) {
double display = 0;
for (int i = 0; i < size; i++) { // for loop
}
cout << "the numbers that you have entered into the array are:" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << endl; // displays numbers entered
}
return display;
}
double GetTotal(double arr[], int size) {
double sum = 0;
for (int i = 0; i < size; i++) {
}
cout << "" << endl;
for (int i = 0; i < 12; i++) {
sum += arr[i];
}
cout << "The sum of all numbers entered is:" << sum << endl;
return sum;
}
double getAverage(double arr[], int size) {
double sum = 0.0, avg;
for (int i = 0; i < size; i++) {
sum = sum + arr[i];
}
avg = sum / size;
return avg;
}
double getLargest(double arr[], int size, int* data) {
double large = 0;
for (int i = 0; i < size; i++) {
if (arr[i] > large) {
large = arr[i];
*data = i + 1;
}
}
return large;
}
double getSmallest(double arr[], int size, int* data) {
double small = 10000;
for (int i = 0; i < size; i++) {
if (arr[i] < small) {
small = arr[i];
*data = i + 1;
}
}
return small;
}
int getNumOccurence(double arr[], int size, int n) {
// only works when you insert repetable number 1
int count = 0;
for (int i = 0; i < size; i++) {
if (n == arr[i]) {
count++;
}
}
return count;
}
double scaleUp(double arr[], int size) {
int factor = 0;
cout << "enter the scale up factor";
cin >> factor;
for (int i = 0; i < size; i++) {
arr[i] *= factor;
cout << arr[i] << endl;
}
return factor;
}
You could use a std::map instead of all those cases.
// Declare a synonym for a function pointer
typedef double (*Function_Pointer)();
// Declare an abbreviation for the map:
typedef std::map<int, Function_Pointer> Function_Display_Table;
// Initialize the function table:
Function_Display_Table display_table;
display_table[0] = display_nums;
display_table[1] = GetTotal;
display_table[2] = getAverage();
//...
// To process your selection:
Function_Pointer fp = display_table.at(selection);
double return_value = fp();
To expand your menu selection, you only have to add rows to the display_table.

how to solve this using Arrays?

I'm new to programming is there a way to solve this:
Take 10 integer inputs from user and print the following
number of positive numbers.
number of negative numbers.
number of odd numbers.
number of even numbers
#include <iostream>
using namespace std;
int main()
{
int numArray[10];
cout<<"Enter Number :";
for(int i=0; i<10; i++)
{
cin>>numArray[i];
}
for(int i=0; i<numArray[i]; i++)
{
if(numArray[i]>0)
{
cout<<"Positive Number "<<numArray[i] <<endl;
}
else
{
cout<<"Negative Number "<<numArray[i]<<endl;
}
if(numArray[i]%2==0)
{
cout<<"Odd number "<<numArray[i]<<endl;
}
else
{
cout<<"even number "<<numArray[i]<<endl;
}
}
return 0;
}
You could do this without arrays but I'm just gonna stick with your original intent for clarity.
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> numArray; //an array of ints, size 10. this is CPP style array, it is 'safer' than C-style array. (someone correct me)
//get your 10 inputs.
cout << "Enter Number :";
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
}
int positive_count = 0;
int negative_count = 0;
int even_count = 0;
int odd_count = 0;
//loop thru your 10 inputs, increment counters accordingly.
for(size_t i = 0; i < numArray.size(); i++)
{
if (numArray[i] < 0)
{
negative_count += 1;
}
if (numArray[i] > 0)
{
positive_count += 1;
}
if (numArray[i] % 2 == 0)
{
even_count += 1;
}
else
{
odd_count += 1;
}
}
cout << "Positive Number " << positive_count << endl;
cout << "Negative Number " << negative_count << endl;
cout << "even number " << even_count << endl;
cout << "Odd number " << odd_count << endl;
return 0;
}
You could do it in input loop:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
odds += numArray[i] & 0x1;
// odds += numArray[i] % 2;
// increment number of positives
positives += (numArray[i] > 0);
// positives += (numArray[i] > 0 ? 1 : 0);
// increment zeros
zeros += !(numArray[i] | 0);
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positive count " << positives << endl;
cout << "Negative Number " << negatives << endl;
cout << "Even number " << evens << endl;
cout << "Odd number " << odds << endl;
and here is newbie friendly version:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
if (numArray[i] % 2 == 1)
odds++;
if (numArra[i] == 0)
zeros++;
else if (numArray[i] > 0)
positives++;
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positives " << positives << '\n';
cout << "Negatives " << negatives << '\n';
cout << "Evens " << evens << '\n';
cout << "Odds " << odds << '\n';

Maximum and minimum values not printing in main () function

I am doing a code on tracking how much food tigers eat in 1 week and I am tracking 3 tigers.
I am supposed to print average, maximum and minimum. Whenever I run the code it doesn't print the max or minimum, only the initialized values I have in the function. I am assuming the int main() ignores my return values completely, but I can't see why is that. I have done many functions before and I do the same code every time and call it in main
Here is the code:
int main(){
cout << "Enter whether you want to find minimum for tiger 1 2 or 3. (Please
only enter 0, 1 or 2): ";
cin >> temp;
if (temp < 0) {
cout << "CAN'T RUN NEGATIVE NUMBERS";
exit(2);
}
least(food, temp, minimum);
cout << "\n";
cout << "The Tiger " << temp << " has minimum: " << minimum << " ";
cout << "\n \n ";
}
float least(float food[][DAYS], int temp, float min) //loop for days only
{
minimum = food[0][0];
//temp has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (min<food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return max;
}
system("PAUSE");
return 0;
}
Since you are not using the return value, use the max and min argument as reference variable in your function definitions. Also the comparison in least & Most functions seems to be wrong. It should be the opposite way.
float least(float food[][DAYS], int temp, float &min) //loop for days only
{
min = food[0][0]; //temp has to be les
for (int j = 0; j < DAYS; ++j) {
if (min>food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return min;
}
float Most(float food[][DAYS], int amb, float &max) //loop for days only
{
max = food[0][0];
//amb has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (max<food[amb][j]) {
max = food[amb][j];
}
}
cout << max << " ";
return max;
}
You do not use your methods' return values. Replace
Most(food, amb, maximum);
and
least(food, temp, minimum);
with
maximum = Most(food, amb, maximum);
and
minimum = least(food, temp, minimum);

Need help calculating AVG of array values (minus the lowest)

So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}
You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}