Strings

Hello! I need help with this program. I have to output the geometric mean of the first 2 digits and last 2 digits of string
for example if user input "84834992" it should take 84 as a and 92 as b
and output geo mean



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  

#include<iostream>
#include<iomanip>
#include<math.h>
#include <string>

using namespace std;

void input( int &a, int &b){

    //cout<<"Input a string of numbers "<<endl;

  // getline (cin,);

}

double matrmoni (int a, int b){
    return (( sqrt(a*b)));
}

void output( double g1 ){

    cout.setf(ios::showpoint|ios::fixed);
    cout<<setprecision(2);
     cout<<"Your Geometric Mean is"<<setw(8)<<g1<<endl;

}

int main(){

    double matrmon1;
    int a, b;
    input(a, b);

    matrmon1=matrmoni(a, b);


    output( matrmon1);

return 0;

}


Last edited on
1
2
3
4
5
6
7
8
9
10
11
void input( int& a, int& b )
{
    cout << "Input a string of numbers: ";
    string input;
    getline( cin, input );

    string first{ input.substr( 0, 2 ) },
        second{ input.substr( input.size() - 2, 2 ) };
    a = stoi( first );
    b = stoi( second );
}


#include<math.h>
math.h is part of the C standard library. Prefer to use cmath instead, in C++.

No need to overuse parentheses. This will work just fine.
1
2
3
4
double matrmoni( int a, int b )
{
    return sqrt( a * b );
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>
#include <cmath>
#include <sstream>

double stringToDouble(const std::string& myString);

int main()
{
    std::string input;
    do
    {
        std::cout << "Enter string: \n";
        getline(std::cin, input);
    } while (input.size() < 2);//need at least 2 digits

    std::string sFront{}, sBack{};
    sFront = input.substr(0, 2);//peel off the first and last 2 digits
    sBack = input.substr(input.size()-2);

    std::cout << std::pow(stringToDouble(sFront) * stringToDouble(sBack), 0.5);
}
double stringToDouble(const std::string& myString)
{
    std::istringstream stream(myString);//create istringstream object with string
    double doubleConvert;
    if(stream)
    {
        stream >> doubleConvert; //read the stream object into double;
    }
    return doubleConvert;
}
We shouldn't be using strings for this program (there would be too many edge cases to take care of):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

int last_two_digits( int n )
{
    if( n < 0 ) return last_two_digits(-n) ;
    else return n % 100 ;
}

int first_two_digits( int n )
{
    if( n < 0 ) return first_two_digits(-n) ;

    while( n > 100 ) n /= 10 ;
    return n ;
}

void get_input( int& a, int& b )
{
    std::cout << "enter an integer: " ;
    int number ;
    // for now, we will assume that the user does enter an integer
    // and not some nonsense like "%&%&BGUGUIG"
    // as it stands, invalid input would yield 0,0 for a,b
    std::cin >> number ;
    std::cout << "number == " << number << "     " ;
    a = first_two_digits(number) ;
    b = last_two_digits(number) ;
}

int main()
{
    int a ;
    int b ;
    get_input( a, b ) ;
    std::cout << "a == " << a << " and b == " << b << '\n' ;

    // compute and print the geometric mean of a and b
}

http://coliru.stacked-crooked.com/a/eaaac111043883b2
Would this address the edge cases?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <cmath>
#include <sstream>
#include <algorithm>

double stringToDouble(const std::string& myString);
bool isDigits(const std::string &str);

int main()
{
    std::string input;
    bool fQuit = false;
    while (!fQuit)
    {
        std::cout << "Enter string: \n";
        getline(std::cin, input);
        if(input.size() >= 2 && isDigits(input))
        {
            fQuit = true;
            break;
        }
        else
        {
            std::cout << "Try again \n";
        }
    }
    std::string sFront{}, sBack{};
    sFront = input.substr(0, 2);//peel off the first and last 2 digits
    sBack = input.substr(input.size()-2);

    std::cout << std::pow(stringToDouble(sFront) * stringToDouble(sBack), 0.5);
}

double stringToDouble(const std::string& myString)
{
    std::istringstream stream(myString);//create istringstream object with string
    double doubleConvert;
    if(stream)
    {
        stream >> doubleConvert; //read the stream object into double;
    }
    return doubleConvert;
}
bool isDigits(const std::string &str)
{
    return std::all_of(str.begin(), str.end(), ::isdigit);//check entire string isdigit
}

Last edited on
Valid input would be rejected: eg. -45678 or +2345 (also valid numbers entered with leading or trailing white space.)

Would give wrong results if the input is 00123456

Alternatively, if "first 2 digits and last 2 digits of string" is interpreted literally, input of 5ab6efgh78i9 should be accepted and should yield 56 and 89.
closed account (48T7M4Gy)
To add further to the apparent impossibility of this exercise who can say the first two characters are decimals? And what is the number base if they aren't? How do you work out the sqrt(5a * i9) in an unknown base?

Is there such a thing as a complex geometric mean? I imagine there is but I haven't checked.

No wonder Western civilization is in decline with such badly framed educational exercises :(

-45678 or +2345
1
2
3
4
5
if (input().front() == '-' || input().front() == '+')
{
	// erase input().front(), check rest of string
	
}

complex geometric mean ...

in reply ...
geometric mean of the first 2 digits and last 2 digits of string

http://home.avvanta.com/~math/def2.cgi?t=digit

input of 5ab6efgh78i9 should be accepted and should yield 56 and 89
the first two characters are decimals

neither would be accepted by isDigits() above in any case
Programmer could define acceptance to let
5ab6efgh78i9
pass if that's what s/he wants

Last edited on
closed account (48T7M4Gy)
@gunnerfunner my good mate

See http://www.oxfordmathcenter.com/drupal7/node/18 on what a digit is. Hex digits are mentioned a few paragraphs down in the article. The point being a digit isn't necessarily a decimal.

You left it hanging about complex geometric means. I'll check one day into this reference and see where it goes, I won't be too fussed if it goes nowhere :) http://planetmath.org/complexarithmeticgeometricmean

Let's not get bogged down gunner because I think most people would accept your response as what is required of students even though there is nothing wrong with going that extra mile (and a half! even) in being absolutely purist and looking at outliers. After all it's part of the deal in good robust programming which mary9734 is probably yet to experience and I sometimes fail on miserably.
Last edited on
The point being a digit isn't necessarily a decimal

Numbers are decimal, hexadecimal, etc, not digits. Neither can digits be negative

BTW I like it that OP is mary9734, there a geometric mean right there if we take JLBorges' interpretation of the problem
closed account (48T7M4Gy)
Illuminating?
https://www.mathsisfun.com/hexadecimals.html
http://mathworld.wolfram.com/Hexadecimal.html

'ma' is a number in some numbering system - pick which one you like because in itself it says nothing about it's base beyond being hexadecimal if we follow the normal convention. There's a hint it might go to at least 'y' as the final digit but not even that is guaranteed. However, if the convention is followed conversion to another base is easily done.

I agree that digits, as numerical symbols, aren't negative in themselves, but they can be used in the appropriate sequence and configuration to represent -ve numbers.
In this problem strings can handle the hexadecimal numbering system since any problem considering this numbering system would state clearly how to handle A-F if they appear in the string i.e as digit or alphabet or upper case as digit, lower case as alphabet &c
closed account (48T7M4Gy)
I would say strings can handle any numbering system whatever way the digits, symbols or cases are arranged. It's fundamental number theory gunner. Hex is understood to be acceptable in upper or lower case regimes, albeit perhaps not mixed.

And besides, upper and lower case are convenient ways to extend a number base system. Use the Greek alphabet or any other squiggles to extend even further if you have a need/application/whatever. It's open-ended.

The beauty about this OP problem is that it hasn't been made clear 'only decimals need apply' so as esoteric as it is if this is a beginner exercise, JLBorges is right in making sure in the interests of robustness

I assume you comment is also in the vein of recognizing now that alpha characters (symbols) can be digits in this context. :)
I would say strings can handle any numbering system


OK, so we agree ... good!
Thank you for help!
Topic archived. No new replies allowed.