Comparing smallest user input for C++ - c++

I tried to find the smallest number within 3 inputs. Here is my codes :
int main ()
{
double x = 4.0;
double y = 5.0;
double z = 3.0;
smallest(x,y,z);
cout << smallest << endl;
system("PAUSE");
}
double smallest(double x, double y, double z)
{
double smallest;
if ((x < y)||(x< z)) {
smallest = x;
} else if ((y < z)||(y < x)) {
smallest = y;
} else {
smallest = z;
}
return smallest;
}
However, I keep getting error. It stated that my smallest method in main method with undeclared identifier. This works when using eclipse but not visual studio. Can somebody explain to me why?
Thanks in advance.
Updated portion.
So I tried to do validation for this program. I want to ensure users only enter number and here are my codes :
double x, y, z;
bool correct_input = false;
do{
cout << "Enter first integer : " ;
cin >> x;
if(isdigit(x)){
correct_input = true;
}
}while(!correct_input);
do{
cout << "Enter second integer : ";
cin >> y;
if(isdigit(y)){
correct_input = true;
}
}while(!correct_input);
do{
cout << "Enter third integer : ";
cin >> z;
if(isdigit(z)){
correct_input = true;
}
}while(!correct_input);
cout << "Smallest integer is : " << smallest(x,y,z) << endl;
system("PAUSE");
When I entered alphabet or whatever except numbers, I get debug assertion failed. It does not prompt until user enter correct input. Can somebody help?

First of all, if you wish to use smallest() before it's defined, you need to prototype it. Add the following before main():
double smallest(double x, double y, double z);
Also, you are ignoring the return value of smallest(). Change
smallest(x,y,z);
cout << smallest << endl;
to
double smallest_val = smallest(x,y,z);
cout << smallest_val << endl;

This isn't the question you asked but your function is bugged because you confused || and &&.
Your function should be
double smallest(double x, double y, double z)
{
double smallest;
if (x < y && x < z)
smallest = x;
else if (y < z && y < x)
smallest = y;
else
smallest = z;
return smallest;
}
x is the smallest number if it is less y and it is less than z.
update
First thing to say is that if you want integers then you should be using int not double.
Second thing, isdigit doesn't do what you think it does. You've actually set yourself a very difficult problem. Here's one way to do it
#include <string> // for string class
bool correct_input = false;
do
{
cout << "Enter first integer : " ;
if (cin >> x)
{
correct_input = true;
}
else
{
// cin is in a error state after a failed read so clear it
cin.clear();
// ignore any remaining input to the end of the line
string garbage;
getline(cin, garbage);
}
}
while(!correct_input);
But this doesn't work perfectly. For instance if you enter abc then your program will ask for more input, but if you enter 123abc, then you will get the integer 123 even though 123abc is not a valid number.
If you really want to do this properly (and it is hard) then you must read in a string, check if the string could be converted to a number, if it can then do the conversion, if it can't then ask for more input.

Put this line above your main ;).
double smallest(double x, double y, double z);
You need to declare any function you make. This is called making a function header.

You should declare you function so that the compiler can recognize it.
Put its prototype above main function as this:
double smallest(double, double, double);
int main()
{
//Staff
}

There are two problem, here, one related to how to get the smallest, and the other related to ho get correct input.
For the first problem, let me propose a recursive approach:
// this is trivial
double smallest(double x, double y)
{ return (x<y)? x: y; }
// the smalles of three is the smallest between the smallest of two and the third
double smallest(double x, double y, double z)
{ return smallest(smallest(x,y),z); }
For the second problem, you have the same problem for each of the variables, so let's make a function for it:
#include <iostream>
#include <limits>
#include <string>
double read(std::istream& s, std::ostream& o, const std::string& message)
{
for(;;) //stay here until kiked out
{
double d=0.; //just a safe value - no particular meaning
o << message << std::endl; // prompt the request
bool good(s >> d); //read a double and keep the state
if(!good) s.clear(); //if we failed to read, clean the stream state
//in any case, discard everything unread until the return.
s.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if(good) return d; //if reading succeeded, return.
//overwise loop back
}
}
This is based on the fact the std::cin have a state that is set to "bad" is the input cannot be read in the given variable.
We just read, and, if it fails, redo again and again.
But fist we have to clear the state, so thet the input can be unlocked.
Independently og good an bad reading, we have then to discard everuthing "extra" that can be typed in the line (think to 123asdf: we successfully read 123, but we have to discard abc)
The the reading was successful we just return it, otherwise we loop over and over until we get it.
The program itself, at this point will reduce to:
int main()
{
double x = read(std::cin, std::cout, "Enter first value");
double y = read(std::cin, std::cout, "Enter second value");
double z = read(std::cin, std::cout, "Enter third value");
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0;
}
that can run this way:
Enter first value
7
Enter second value
5.2yyyy
Enter third value
sf3
Enter third value
455
the smallest numer is: 5.2
A more advanced technique can be transform the function into a manipulator class, like this:
class read_value
{
public:
read_value(double& d, const std::string& prompt_, std::ostream& out_ = std::cout)
:z(d), prompt(prompt_), outstream(out_)
{}
friend std::istream& operator>>(std::istream& s, const read_value& a)
{
for(;;)
{
a.outstream << a.prompt << std::endl; // prompt the request
bool good(s >> a.z); //read a double and keep the state
if(!good) s.clear(); //if we failed to read, cleanr the stream state
//in any case, discard everything unread until the return.
s.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if(good) return s; //if reading succeeded, return.
//overwise loop back
}
}
private:
double& z;
std::string prompt;
std::ostream& outstream;
};
letting the program a more idiomatic form:
int main()
{
double x,y,z;
std::cin >>
read_value(x,"Enter first value") >>
read_value(y,"Enter second value") >>
read_value(z,"Enter third value");
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0;
}
Another point can be the fact the user can loop forever by never typing a good sequence.
We can fix a maximum attempt limit introducing a counter in the for loop, and setting the input to "failed" if the loop terminates without returning:
friend std::istream& operator>>(std::istream& s, const read_value& a)
{
for(int i=0; i<10; ++i)
{
... //same as before
}
return s; //s will be returned in failed state
}
And then checking in the main program:
int main()
{
double x,y,z;
std::cin >>
read_value(x,"Enter first value") >>
read_value(y,"Enter second value") >>
read_value(z,"Enter third value");
if(!std::cin)
{
std::cout << "bad input." << std::endl;
return -1; //report as "program failed"
}
std::cout << "the smallest numer is: " << smallest(x,y,z) << std::endl;
return 0; //succeeded
}
.

Related

using fmod in a function, loop logic is returning unexpected value

I am writing a program that takes the cost of an item, and the amount payed, and calculates how much of each coin you should get back in change (quarter, dime, nickel, penny). In the function that is calculating how many quarters are needed back, it always returns 2
float calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmod(change, (.25 * x));
x++;
}
return x;
I am not sure what is wrong.
Also, excuse my inefficient code and probably ugly code, I am still learning
#include <iostream>
#include <math.h>
using namespace std;
float calculateChange(float, float);
float calculateCoins(float);
int main()
{
float amountPay, amountDue, changeDue, quarter;
cout << "This program calculates how much change should be returned "
<< "\nwhen a payment is made" << endl << endl;
cout << "Please input the cost of the item:" << endl;
cin >> amountDue;
cout << endl << "Please input the amount paid:" << endl;
cin >> amountPay;
changeDue = calculateChange(amountDue,amountPay);
quarter = calculateCoins(changeDue);
cout << changeDue << endl;
cout << quarter << " quarters needed";
return 0;
}
float calculateChange(float amount, float payment)
{
return payment-amount;
}
float calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmod(change, (.25 * x));
x++;
}
return x;
}
Your problem is, that the logic behind function calculateCoins(float change) is wrong.
You first initialize result with a value of 1.
In your loop, you check against result > 0.
In your first iteration, this will always be true since you have initialized result with 1. In your loop body, you change the value of result to the modulo and increase your value of x which is now 2. The loop only stops, if the modulo of your change and x is 0. This is clearly not what you expect.
Try this:
cost = 1.1
paid = 2
and you end up with an infinite loop.
take this as a start point:
float calculateCoins(float change)
{
int x=1;
float result=1;
while (change - x*0.25 > 0)
{
x++;
}
return x;
}
I'm not sure what your expected result is.
Try to figure out what happens if you input strange numbers like cost = 1.1 paid = 2.
#D-Russ. First your function CalculateCoins is returning an int but you demand a float as output. If this is what you really want, consider casting the result before returning it. Second, you should use the appropriate remainder function from the math library.
Your code could change to the following:
int calculateCoins(float change)
{
int x=1;
float result=1;
while (result>0)
{
result =fmodf(change, (.25f * x)); // Note the use of "fmodf"
x++;
}
return x;
}
In fact, the number of quarter returned is an int, doesn't it make sense.
Note that in my suggested function, instead of float CalculateCoins(float change), I wrote int CalculateCoins(float change).

Set double variable to value of another variable

I'm sure I'm missing something simple here. With the code I've posted, how do I set the double 'condition' to the value of the double 'interstate' ?. I thought by entering 'interstate' as the answer to my 'cout' question would work. The calculation I get is garbage.
double multiplyAmount(double overage)
{
double interstate = 1.25;
double countyRd = 2.23;
double condition;
double result;
cout << "Enter condition of road: ";
cin >> condition;
result = overage * condition;
return result;
}
Variable names are purely lexical, meaning they do not exist outside of compilation process (e.g. do not exist at runtime when user enters something).
There are many ways to achieve what you want.
Here's one of them:
#include <string>
double multiplyAmount(double overage)
{
double interstate = 1.25;
double countyRd = 2.23;
double condition;
double result;
string conditionInput;
cout << "Enter condition of road: ";
cin >> conditionInput;
if(conditionInput=="interstate") {
condition = interstate;
} else if(conditionInput=="countryRd") {
condition = countryRd;
} else {
cout << "Unknown condition" << conditionInput << std::endl;
abort();
}
result = overage * condition;
return result;
}

C++ Even or Odd number program not working properly

I'm new to C++, and I was doing the exercise found here:
http://www.learncpp.com/cpp-tutorial/32-arithmetic-operators/
I was doing quiz 2 which tells me co create a program that receives an integer from user, and prints true of that integer is even. So I created the following code:
#include "stdafx.h"
#include <iostream>
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int8_t x;
std::cin >> x;
return x;
}
bool isEven(int8_t x)
{
bool b;
b = false;
std::cout << x % 2 << "\n";
if(x%2 == 0)
{
b = true;
}
return b;
}
void printResult(bool b)
{
std::cout << std::boolalpha;
std::cout << b << "\n";
}
int main()
{
int8_t x;
x = getInteger();
bool b;
b = isEven(x);
printResult(b);
return 0;
}
So, here is the problem. Unless I'm missing something, this should work, right? And it does, but only for integers that I input from 0 to 10. For some reason, if I input 10, or 12, it prints false, but it works fine with 2, 4, 6, and 8. Why is this happening?
You have following code:
int8_t x;
std::cin >> x;
int8_t is just an alias for char for your platform and std::istream when it has type char as argument inputs one character, not integer. So solution would be to use type int and you should use it from the beginning as there is no reason at all to use int8_t in this case.
This function returns a different type than the one it supposed to return:
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int8_t x;
std::cin >> x;
return x;
}
int should work fine instead of int8_t and see here why Documentation
As you have it getInteger() takes character text translated input, not numbers., since int8_t actually expands to char
To fix that take a integer number in 1st place and cast to the int8_t type:
int getInteger()
{
std::cout << "Insert an integer" << "\n";
int x; // <<<<
std::cin >> x;
return x;
}
x = (int8_t)getInteger();
The reason that Alex on learncpp.com specifies that it is better to use fixed width integers is because the results of the program will not vary when it is compiled on different compilers. This is not the case for non-fixed-width integral types like char and int, since the size of the type will vary between compilers. As #Slava points out, int8_t is a fixed width integral type for char, so both are used with variables that will only store a single character in memory.
Use fixed width integers whenever the program may be used in a different compiler or machine and it is important that the results will be compiler- and platform-independent. Because the program is asking for user input for any integer, to use a fixed width integer, it would be best to use int32_t. int8_t and 'char' would be suitable for getting digits (i.e. 0–9). int16_t is suitable for integers between -2^16/2 (which equals -2^15) and 2^15-1 (i.e. between -32 768 and 32 767). 'int32_t' is suitable for integers between -2^31 and 2^31-1 (i.e. between -2 147 483 648 and 2 147 483 647).
As Alex explains later in 5.10 — std::cin, extraction, and dealing with invalid text input, it is important to handle all possible invalid user inputs.
Here is some updated code that will work, handle invalid user inputs, and loop to ask the user if they want to check whether another number is even or odd, and so do:
// StackOverflow C++ Even or Odd number program.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream> // for cin and cout
//include <cmath> // pow is no longer used and is commented out below.
#include <cstdint> // std::int32_t
// I changed the variable output for the function to int32_t, since that is the type being returned.
std::int32_t getInteger()
{
/* If you don't understand some parts, like do-while loops and
handling invalid user input, come back to it after learning it,
and just focus on what you can understand.
*/
// Use int32_t since the user input could potentially be a very large number.
std::int32_t x{ 0 };
bool notInt32t = 1;
bool cinFail{1};
do
{
// Don't use an '/n' character when getting user input, it makes more sense to get it on the same line as the prompt.
std::cout << "Enter an integer: ";
std::cin >> x;
cinFail = std::cin.fail();
if (cinFail)
{
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "Oops, that input is invalid. This may be because you entered a number larger \n";
std::cout << "than 2147483647 (which equals 2^31-1), or less than -2147483648 (which equals -2^31); \n";
std::cout << "or you did not enter an integer only. Please try again.\n";
}
// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
else
std::cin.ignore(32767,'\n');
/*Commented out because this will not work, it will fail to extract. Left in the code for education purposes.
notInt32t = ((x > (pow(2.0, 31.0) - 1)) || (x < -pow(2.0, 31.0)) || !(x % 1 == 0));
if (notInt32t)
std::cout << "Oops, you entered incorrectly!\n";
*/
} while (cinFail);
return x;
}
bool isEven(std::int32_t x)
{
bool isEven;
isEven = (x % 2 == 0) ?(true):(false);
return isEven;
}
/* I have commented this out and rewrote it, as it is ambiguous.
void printResult(bool b)
{
std::cout << std::boolalpha;
std::cout << b << "\n";
}*/
void printIsEven()
{
auto x = getInteger();
if (isEven(x))
std::cout << x << " is an even integer.\n";
else
std::cout << x << " is an odd integer.\n";
}
void printIsEvenLoop()
{
std::int8_t yOrN{};
bool isLoop{ true };
bool cinFail{ false };
bool isYOrN{ false };
while (isLoop)
{
do
{
std::cout << "Would you like to check whether another integer is even or odd?\n";
std::cout << "Enter y or n (yes or no): ";
std::cin >> yOrN;
cinFail = std::cin.fail();
if (cinFail)
{
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "Oops, that input is invalid! Please try again.\n";
}
// remove any extraneous input, which would otherwise be left in the buffer, causing unexpected results.
else
std::cin.ignore(32767, '\n');
isYOrN = ((yOrN == 'y' || yOrN == 'n'));
if (!isYOrN)
std::cout << "Oops, you entered incorrectly! Please try again.\n";
} while (cinFail || !isYOrN);
if (yOrN == 'y')
{
isLoop = true;
printIsEven();
}
else
isLoop = false;
}
}
int main()
{
printIsEven();
printIsEvenLoop();
return 0;
}

Program in c++ tell if a number is integer or float

I used function overload to check if an input number is integer or float. However I get this following error:
error: call of overloaded 'retNr(double)' is ambiguous|
#include <iostream>
using namespace std;
void retNr(int x)
{
cout << "The entered number is an integer. " << endl;
}
void retNr(float x)
{
cout << "The entered number is a float. " << endl;
}
int main()
{
cout << "Please enter a number: " << endl;
cin >> nr;
retNr(nr);
return 0;
}
Read from cin into a string and then check the string for the presence of a decimal point. If there is a decimal point, call atof() on the string to convert it to a float, otherwise call atoi() to convert it to an integer.
Make some small change in:
void retNr(double x)
{
cout << "The entered number is a double. " << endl;
}
Remember to declare your nr variable.
double d = 1.0;
int i = 1;
retNr(d);
retNr(i);
You will have to initialize nr first.
Then you can use integer read & check it with a float if there is dot, ie ch=='.'
Thus, your program will be like this:
#include <iostream>
using namespace std;
int main()
{
int nr = 0; char ch;
cout << "Please enter a number: " << endl;
cin >> nr;
cin.get(ch);
if(ch=='.')
{
cout << "The entered number is a float. " << endl;
}
else
{
cout << "The entered number is an integer. " << endl;
}
return 0;
}
It's not too clear what you're asking for. If you really want
to know whether a number is an integer or not, then use modf
on it:
bool
isInt( double d )
{
double dummy;
return modf( d, &dummy ) == 0.0;
}
If you're reading a number, then read it as a double, and then
use the above.
If you want to trigger off the format of the input (i.e.
"10.0" will be treated as a floating point, even though it is
an integer), then read the input as a string, then try to
convert it to int; if this eats all of the input, then it was
entered as an int (no decimal or exponent), otherwise, try the
same thing treating it as a double:
std::string entry;
std::cin >> entry;
char const* end;
long i = strtol( entry.c_str(), &end, 10 );
if ( *end == '\0' ) {
// entry was entered in integral format...
} else {
double d = strtod( entry.c_str(), &end );
if ( *end == '\0' ) {
// entry was entered in floating point format...
} else {
// entry wasn't a number...
}
}
I'd advise against this, however; it will only confuse your
users if 0 isn't 0.0.
You may use abs() function for this issue.
#include<stdio.h>
#include<math.h>
int main()
{
double input;
scanf("%lf",&input);
int absulate = abs(input);
printf( (input==absulate)? "It is integer\n" : "It is float");
return 0;
}
float num = 7;
int n = (int)num;
float n1 = (float)n;
if(num == n1)
{
cout << "Integer\n";
}
else
{
cout << "Not Integer\n";
}
The question is wrong in its essence: A number it is not a float or an integer, but could be represented as a float or as an integer ( of course certain representation has some limitations )
So if I wrote '10' why should I say this is an integer? Could be a float too! Just if I want to use it as a float I would represent it as a float.

Why does my C++ divide program not compile

I tried to make a program that has a correct Divide function.
My code was:
#include <iostream>
using namespace std;
double x,y,z,a;
double divide(x,y) {
if (x >= y) {
x=z;
z=y;
y=x;
return(x/y);
}
else
return(y/x);
}
int main()
{
double x,y,z ;
cout << "Enter x " <<endl;
cin >> x;
cout << "Enter y " <<endl;
cin >> y;
a = divide (x,y);
cout << a <<endl;
system("pause");
return 0;
}
And I have 2 errors:
expected `,' or `;' before '{' token
on the { line. Right under the double divide (x, y) line
And another error
divide cannot be used as a function
on the a = divide (x, y); line.
I am using Code: Blocks
You need to specify a proper function signature for the function divide. Specifically, the arguments to the function are missing their types:
double divide(double x, double y)
{
...
}
You also need to create a scope for each block in an if statement:
if (x > y)
{
...
}
else
{
...
}
The braces in an if statement don't go around the else block. You need a separate pair of braces there. Try:
if (x >= y){
x=z ;
z=y ;
y=x ;
return(x/y);
}
else {
return(y/x);
}
The second set of braces (around the one line of the code after the 'else' aren't strictly necessary; you can leave the braces off an if or an else if the block is only one line long. But while you're new you probably shouldn't, as it's easy to make mistakes that way.
Also, you have not provided types for the x and y variables in your divide function. You must specify types for them, just as you would for any other variable. You've written
double x,y,z,a ;
...outside of the function, but that doesn't help; it defines new double variables named x, y, z,and a, completely independent of the ones in your function.
Corrected your braces in your if...else. also need to define a type in your function's parameters.
using namespace std;
double x,y,z,a ;
double divide (double x, double y)
{
if (x >= y){
x=z ;
z=y ;
y=x ;
return(x/y);
}
else
{
return(y/x);
}
}
int main()
{
double x,y,z ;
cout << "Enter x " <<endl;
cin >> x ;
cout << "Enter y " <<endl;
cin >> y ;
a = divide (x,y);
cout << a <<endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
// divides x/y
double divide (x,y)
{
if(y != 0)
{
/*{} <- this is called a scope.
it is important to keep track of scopes.
each function has it's own scope
each loop or an if instruction can have it's own scope
in case it does - all the instructions from the scope will be executed
in case it doesn't - only the 1st instruction after the if/else/for/while etc. will be executed
Here's another funny thing about scopes :
{
double x; // this variable exists ONLY within this scope
}
{
// y doesn't exist here
{
double y; // y exists here. it's local
}
// y doesn't exist here
}
*/
return x / y;
}
else
return 0;
}
int main()
{
double x,y;
cout << "Enter x " <<endl;
cin >> x ;
cout << "Enter y " <<endl;
cin >> y ;
double a = divide (x,y);
cout << a <<endl;
cin;
return 0;
}