Hi,
the code below is a simple program. this is my question and problem
1: how to disallow the user to input char or string?
2: disallow the user to enter a neg number.
First, do not use global variables. It is a bad habit.
Second, comparing a float against 0 is risky, because floats are internally stored as discrete binary values. Weird things will bite you, if you think that floats behave as in math.
Why does cost() return a float? void is a valid return type.
Why floats in general?
isdigit() can tell you whether a character that you have is a digit. cin >> into a float stores nothing, if user types something else. However, cin will have failbit set.
1 2
if ( cin.good() && 0.0f < choice ) ...
elsebreak;
Now the loop continues as long as the user types positive numbers. Remember, that if !cin.good(), then cin remains in non-good state after the loop, and should be cleared before next use.
#include <iostream>
#include <math.h>
usingnamespace std;
float cost ()
{
//to calculate the ammo needed
float apple;
float orange;
float pear;
apple = choice * 16;
orange = choice * 40;
pear = choice *6;
cout << endl;
cout << "You will need\n" << apple << " to buy apple.\n" << endl;
cout << "You will need\n" << orange << " to buy orange.\n" << endl;
cout << "You will need\n" << pear << " to buy pear.\n" << endl;
return 0;
}
int main()
{
//title for the user.
//also telling the user how to end the program.
cout << "\n\tThis is a program that calculate numbers" << endl;
cout << "\n\tEnter 0 to exit." << endl;
float choice;
while (1)
{
cout << "\nEnter a number? : ";
cin >> choice;
if (choice != 0)
{
cost ();
}
else
{
cout << "You are ending this session." << endl;
break;
}
}
return 0;
}
i have change the code and remove all global variables. and when i run the code, i this what i get
1 2 3 4 5
Compiling: main.cpp
D:\programming\C++\test1\main.cpp: In function 'float cost()':
D:\programming\C++\test1\main.cpp:12: error: 'choice' was not declared in this scope
Process terminated with status 1 (0 minutes, 0 seconds)
1 errors, 0 warnings
in this case where should i place "choice"?
thanks.