Any tips on how to add up the total frabjous numbers in my code?
#include<iostream>
#include<string>
using namespace std;
const int FRABJOUS_NUMBER = 7;
int main(void)
{
while (true)
{
// input two non negative numbers w/ loop
///////////////////////////////////////////
int firstValue, secondValue;
while (true)
{
cout << "Enter low and high bounds for a range of integer values: ";
cin >> firstValue >> secondValue;
cin.ignore(999,'\n');
if ( cin.fail() )
{
cin.clear();
cin.ignore(999,'\n');
cout << "Non-numeric input, try again." << endl;
continue;
}
if (firstValue < 0 || secondValue < 0)
{
cout << "Negative input, try again." << endl;
continue;
}
break;
}
// sort the minimum and maximum in range
////////////////////////////////////
int rangeMinimum, rangeMaximum;
if (firstValue > secondValue)
{
rangeMaximum = firstValue;
rangeMinimum = secondValue;
}
else
{
rangeMinimum = firstValue;
rangeMaximum = secondValue;
}
// introduce inbetween integers of desired range
////////////////////////////////
int inbetweenInteger = rangeMinimum;
while (inbetweenInteger < rangeMaximum)
{
++inbetweenInteger;
}
// checks for every value within range minimum and maximum
// decide if integer is frabjous
//////////////////////////////////////////////////////////
int totalFrabjous_numbers = rangeMinimum + inbetweenInteger + rangeMaximum;
while (true)
{
if ( (rangeMinimum /= 10) == FRABJOUS_NUMBER)
{
totalFrabjous_numbers++;
}
else
if ( (rangeMinimum % 10) == FRABJOUS_NUMBER)
{
totalFrabjous_numbers++;
}
If you want to know whether a number contains a '7', stream it into a string (use stringstream), then test for the character '7'. If it fulfils this criterion add the original number to a rolling sum.
Your range of integers can easily be dealt with by a for loop. No idea why your code above is so complex.
#include <iostream>
#include <sstream>
usingnamespace std;
bool isFrabjous( int n );
int main()
{
int n1, n2;
int sum = 0;
cout << "Input range (min max): ";
cin >> n1 >> n2;
for ( int n = n1; n <= n2; n++ ) if ( isFrabjous( n ) ) sum += n;
cout << "Sum is " << sum;
}
bool isFrabjous( int n )
{
stringstream ss;
ss << n;
return ( ss.str().find( "7" ) != string::npos );
}