Biggest Number Function in C++ - c++

void biggest_number() {
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
first_input = big_num;
//cout << first_input;
while (1) {
cin >> input;
if (big_num < input) {
input = big_num;
}
else if (input == 0) {
cout << big_num;
break;
}
else{
}
};
};
So I've written a function to find the biggest number. But whatever I put as an input, big_num always comes out as 0.
I've tried to use cout <<first_input << big_num; in order to find out where the function doesn't work. You can see from the comment. That part doesn't work and I couldn't figure out why.

You have the assignment first_input = big_num; reversed. It should be big_num = first_input;

float big_num;
You declare big_num but haven't assigned it a value, so big_num is uninitialized. So big_num can hold any value. Then, you assign first_input to equal big_num. So both first_input and big_num is holding random values.
It seems kind of strange to me that you input first_input, then immediately you assign first_input to equal big_num. I think that you meant the other way around.
big_num = first_input;
Also:
void biggest_number() {
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
first_input = big_num;
//cout << first_input;
while (1) {
cin >> input;
if (big_num < input) {
input = big_num;
}
else if (input == 0) {
cout << big_num;
break;
}
else{
}
}; // <-- here
}; // <-- and here
There is two unnecessary semicolons. You should remove it.
note: using namespace std; is bad practice, so avoid using it.

void biggest_number()
{
float first_input;
float big_num;
float input;
cout <<"\n You've chosen to Find out The Biggest Number. Type in number to compare\nType 0 if you want to stop the function.\nFirst number : ";
cin >> first_input;
big_num = first_input;
cout << "Second number :";
while (1)
{
cin >> input;
if (first_input < input)
{
big_num = input;
cout<< big_num << " Is the big number" << endl;
break;
}
else if (input == first_input)
{
cout << "Both inputs are same" << endl;
break;
}
else
{
cout<< big_num << "Is the big number" << endl;
break;
}
}
}
int main()
{
cout<<"Hello World";
biggest_number();
return 0;
}

See #justANewbie's answer about the actual problem (mixing up your input and big_num variables).
I just wanted to provide a more compact solution. It's not important that the code is short in this case, but you might learn some more convenient C++ coding tricks/styles from it. Additionally, it's sometimes easier to spot errors when the code is compact and has less branching.
This solution uses a common C++ pattern you might call "read while":
#include <cmath> // for INFINITY
#include <iostream>
void biggest_number() {
float biggest = -INFINITY;
// while we can read a number and it's not zero
for (float input; (std::cin >> input) && input != 0; ) {
// keep track of biggest number found
if (input > biggest) biggest = input;
}
std::cout << biggest;
}

Related

How can I ignore any string that the user inputs?

The user should input a double but how would I get the program to ignore a string or a char if they put one in. The problem with my current code is when I put in a string the program will spam and fill the screen with the cout << "What is the length of the rectangle";
double length;
do {
cout << "What is the length of the rectangle: ";
cin >> length;
bString = cin.fail();
} while (bString == true);
do {
cout << "What is the length of the rectangle: ";
cin >> length;
bString = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (bString == true);
This is the code I found that works for my issue.
cin.fail() will not differentiate between integers and floating point numbers.
The best way to check is by using std::fmod() function to check if the reminder is more than zero. if it is then its a floating point number.
Here is the code
#include <cmath>
int main()
{
double length;
std::cout <<"What is the length of the rectangle: ";
std::cin >> length;
if (std::cin.fail())
{
std::cout<<"Wrong Input..."<<std::endl;
} else
{
double reminder = fmod(length, 1.0);
if(reminder > 0)
std::cout<<"Yes its a number with decimals"<<std::endl;
else
std::cout<<"Its NOT a decimal number"<<std::endl;
}
}
Beware that this code will not differentiate between 12 and 12.0.
If the user inputs an invalid data type, cin will fail. You can check using this
double length;
while(true)
{
std::cout << "What is the length of the rectangle: ";
std::cin >> length;
if (std::cin.fail())
{
std::cout << "Invalid data type...\n";
std::cin.clear();
std::cin.ignore();
}
else
{
break;
}
}

IF or WHILE for numerical input checker

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

How can you make input take strings and int? c++

is it possible, say your trying to do calculations so the primary variable type may be int... but as a part of the program you decide to do a while loop and throw an if statement for existing purposes.
you have one cin >> and that is to take in a number to run calculations, but you also need an input incase they want to exit:
Here's some code to work with
#include <iostream>
using namespace std;
int func1(int x)
{
int sum = 0;
sum = x * x * x;
return sum;
}
int main()
{
bool repeat = true;
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (repeat)
{
int input = 0;
cin >> input;
cout << input << " cubed is: " << func1(input) << endl;
if (input = "leave" || input = "Leave")
{
repeat = false;
}
}
}
I'm aware they wont take leave cause input is set to int, but is it possible to use a conversion or something...
another thing is there a better way to break the loop or is that the most common way?
One way to do this is read a string from cin. Check its value. If it satisfies the exit condition, exit. If not, extract the integer from the string and proceed to procss the integer.
while (repeat)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
repeat = false;
}
else
{
int intInput = atoi(input.c_str());
cout << input << " cubed is: " << func1(intInput) << endl;
}
}
You can read the input as a string from the input stream. Check if it is 'leave' and quit.. and If it is not try to convert it to a number and call func1.. look at atoi or boost::lexical_cast<>
also it is input == "leave" == is the equal operator. = is an assignment operator.
int main() {
cout << "Enter a value to cube: " << endl;
cout << "Type leave to quit" << endl;
while (true)
{
string input;
cin >> input;
if (input == "leave" || input == "Leave")
{
break;
}
cout << input << " cubed is: " << func1(atoi(input.c_str())) << endl;
}
}
you can use like
int input;
string s;
cint>>s; //read string from user
stringstream ss(s);
ss>>input; //try to convert to an int
if(ss==0) //not an integer
{
if(s == "leave") {//user don't want to enter further input
//exit
}
else
{
//invalid data some string other than leave and not an integer
}
}
else
{
cout<<"Input:"<<input<<endl;
//input holds an int data
}

Comparing Doubles and Chars in C++

I am trying to write a simple program in C++ that reads in an unspecified number of marks, then once the user inputs the character 'q', the program must calculate and display the average mark. However I am having some trouble. The approach I am taking is to save each value as a double, the I want to compare the double to the character 'q' and if they are the same character, end the loop, calculate and display the average.
However I think that the comparison between the char value 'q' and double value for the mark seem to be incomparable. This worked for me when I did the same using integer values for the mark but not doubles it seems. Any help would be appreciated.
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if (mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you'll need to change the mark variable to string, and then compare it to 'q', else try to parse is as a number.
otherwise this entire code, does not make a lot of sense, because 'q' in ASCII is 113, which I guess is a possible value
Typecast double to int and then compare, It must work because it compares ASCII value of character
Here is the code:
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
double mark;
cin >> mark;
if ((int)mark != 'q')
{
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "Average: " << average << endl;
return 0;
}
you can not cast a double to char. You may need to use additional c++ library functions which convert string (char*) to double. There are different ways to do this.
Try this :
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
cout << "Please enter any number of marks. Enter 'q' to stop." << endl;
double total = 0;
int counter = 0;
bool repeat = true;
do
{
char userinput[8];
cin >> userinput;
std::stringstream ss;
double mark;
if (userinput[0] != 'q')
{
ss << userinput;
ss >> mark;
total += mark;
counter++;
}
else
{
repeat = false;
}
}
while (repeat == true);
double average = total/counter;
cout << "total : " << total << " count : " << counter << endl;
cout << "Average: " << average << endl;
return 0;
}
You are doing it wrong. If you try to cin a char into a double variable, the input char stays in the input buffer and the double variable remains the same. So this will end in an infinite loop.
If you really want the user to enter a char to end input, you need to take the whole input in a string variable. Check the string for q. If not present, use atof() to convert it to double.

c++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;