I have a function that parses user input into the correct overloaded function. My "parseUserInput" function determines if the user entered a character, a floating-point, or an integer array. Then it calls the overloaded function to ultimately determine the average grade. The problem I am facing is, when I enter an integer array, I want to ensure if the user doesn't enter 5 integers, that the rest get filled in with zeros.
Example: "55 66 98 32 87" would work.
Example: "55 66" would not work... I want the compiler to understand the missing variables should be auto-filled to zero, such as .... " 55 66 0 0 0".
Any thoughts on how I can do this?
void parseUserInput(char *userInput)
{
int array[ASSGN_MARK];
/* other code ... */
else if (sscanf(userInput, "%i %i %i %i %i", &array[0], &array[1], &array[2], &array[3], &array[4]))
{
printf(">> This input should be directed to the << assessGrade(int[]) >> function ...\n");
assessGrade(array);
}
/* other code...*/
}
//Overloaded Function
void assessGrade(int array[ASSGN_MARK])
{
int total = 0;
int sum = 0;
sum = array[0] + array[1] + array[2] + array[3] + array[4];
total = sum / ASSGN_MARK;
//being type-casted to a double, as I'm calling the next overloaded function
//and that overloaded function will display if the student passed or failed
assessGrade((double)total);
}
As this is a C++ question, I recommend you do it the C++ way, and use std::vector. You can initialize the elements to zero like this:
std::vector < int > array(5, 0);
You'll also need to pass a reference, create a class to put both functions in, or make it global, because the way you have it right now, the other function can't see array.
I've figured out how to make these two functions work..
First, I've changed my function prototype to use default parameters. Therefore, if the user doesn't enter a number the number gets defaulted to 0.
void parseUserInput(char *userInput)
{
/* other code... */
else if (sscanf(userInput, "%i %i %i %i %i", &a, &b, &c, &d, &e))
{
printf(">> This input should be directed to the << assessGrade(int[]) >> function ...\n");
assessGrade(a, b, c, d, e);
}
/* other code... */
}
void assessGrade(int a, int b, int c, int d, int e)
{
int total = 0;
int sum = 0;
sum = a + b + c + d + e;
total = sum / 5;
assessGrade((double)total);
}
Related
I'm kind of inexperienced with C++, and I'm converting a program that I wrote in C to C++. I have a RollDice function that takes numbers that I read in from a text file and uses them to generate the number. This is the function in C:
void rollDice(Move *move, GameState *game_state) {
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = game_state->randomNums[game_state->current_roll]; //gets the random number from the array randomNum (which holds the numbers from the text file), at index "current_roll"
game_state->current_roll++; //increments so the next random number will be the next number in the array
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = game_state->randomNums[game_state->current_roll];
game_state->current_roll++;
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move->dice_sum = diceNum1 + diceNum2;
printf("You rolled a %d!\n", move->dice_sum);
}
This works just how I want it to when I run it. Now, when converting my program to C++ I had to change things around. My parameters are now pass by reference and I made a vector to store the list of random numbers from the text file:
void rollDice(Move& move, GameState& game_state) {
std:: vector<int> randomNums = game_state.getRandomNums();
int current_roll = game_state.getCurrentRoll();
int diceNum1 = 0;
int diceNum2 = 0;
int randomNumber1 = 0;
int randomNumber2 = 0;
randomNumber1 = randomNums.at(current_roll);
current_roll++;
diceNum1 = 1 + (randomNumber1 % (1 + 6 - 1));
randomNumber2 = randomNums.at(current_roll);
current_roll++; //this line is grayed out and says "this value is never used"
diceNum2 = 1 + (randomNumber2 % (1 + 6 - 1));
move.dice_sum = diceNum1 + diceNum2;
std:: cout << "You rolled a " << move.dice_sum << "!\n";
}
My code is telling me that the second time I increment current_roll it is unused. This didn't happen for my C code, so why is it happening here and how can I fix it? I'm completely lost.
It's never used because you write to the variable, but never read from it. Having a variable that you never read is effectively meaningless.
Presumably your game_state.getCurrentRoll function returns an integer, when you store this, you store the value (rather than a reference to the value), thus incrementing it doesn't increment the current roll inside the game_state, instead you should add a function to your game_state called makeRoll for example which increments the game_states internal current_roll value.
This is different from your C code which increments the current_roll value directly using game_state->current_roll++ (alternatively you could make game_state.current_roll public and increment it the same way as in your C code).
From your comment I assume you have some class:
class GameState {
private:
int current_roll;
...
public:
int getCurrentRoll() {
return current_roll;
}
...
}
All you'd need to do is add another function to your class to increment the current_roll:
class GameState {
private:
int current_roll;
...
public:
int getCurrentRoll() {
return current_roll;
}
void makeRoll() {
current_roll++;
}
...
}
Then you can call it as normal.
Regarding your new issue in the comments regarding the error:
parameter type mismatch: Using 'unsigned long' for signed values of type 'int'.
This is because the signature of at is std::vector::at( size_type pos ); That is, it expects a value of type size_type which is an unsigned integer type, rather than int as you're using which is signed. This post may be helpful.
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
In the following code:
int sum(int a=40, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
int a = 100;
int b = 200;
int result;
result = sum(a, b);
cout << "Total value is :" << result << endl;
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
This produces:
Total value is : 300
Total value is : 120
Why does the:
sum(a)
add the (int a) in the 2nd block to the (int b) in the 1st block?
Im confused why the (b) value in the 1st block is used in (sum(a)), but the (a) value in the 1st block is ignored.
int sum(int a=40, int b=20) {
...
}
declares the parameters a to be 40 and b to be to 20, if not specified. This is a compiler service, so sum(a) becomes sum(a, 20) (b not specified). Similar to this, sum() becomes sum(40, 20). a and b in your method sum are default parameters.
In function sum you are using default arguments. That's why when you call
result = sum(a); // where a = 100 and the second parameter is ommited
in the function sum, the first parameter is take the value of this caller's a (= 100), and as the second parameter is absent from the caller's end, the default b (= 20) will be used as b. Hence the result is
100 + 20
= 120
As David RodrÃguez suggested in the first comment, use different variables name (say sum (int x, int y)) for no ambiguity and better understanding.
In order to make it shorter:
int sum(int a=40, int b=20)
{
return a + b;
}
int main ()
{
int a = 100;
int b = 200;
cout << "Total value is :" << sum(a, b) << endl;
cout << "Total value is :" << sum(a) << endl;
return 0;
}
In the sum(a,b) both of the parameters have values => it does a+b => 100 + 200 which is 300.
In the sum(a) the second parameter is not set, the function use the default value (ie: 20) => a + 20 => 100 + 20 which is 120
The a & b you define in your main are not the one of the sum function
Well, you should read a bit about default parameters in C++. Where you are on it, I recommend you to research a bit about overloading, since they are somewhat related.
On the first call you do to the sum() function, you provide both parameter to the call, so the variables a and b ,that you declared, are used, hence you get 100+200=300. On the second call tho, you only provide one parameter, so the second one uses the default parameter value, i.e. a=100, b gets the default value (20), so you get 100+20=120.
When you write a function like
returntype Function_name(data_type some_value), then this is called default parameters.
For eg: if you write a function like,
int calculate_area(int lenght=20, int width=25)
Then when you call this function from main, you can either pass values to length and width like this,
int main() {
int a=50;
int b=60;
calculate_area(a,b);
}
Or you can call it like this...
int main() {
calculate_area();
}
See the difference, we are not passing any parameter, still it is a valid call to the function, because in this case.... the default values mentioned by you for length and width will be considered, which in this case is 20 & 25.
And about variables 'a' & 'b' in your code, looks like you are getting confused between name of the variables. Main() and Sum() are two different functions.
'a' of sum has nothing to do with 'a' of main. You will understand this when you will read how the variables are stored in stack and all.
I am dealing with a programming question where I need to divide a very big number, of the order of 10^50000 by another of the order of 1000, in order to figure out if one is divisible by the other. So I need to use strings to store this large number.
I don't know any method to divide a string by a number. Can anyone point me to an algorithm?
Here is a start of an algorithm. It seems to do what you are asking for: it performs "long division" in 4 character chunks, and keeps track of the remainder. It prints the remainder at the end. You should be able to adapt this to your specific needs. Note - doing this in 4 bytes chunks makes it significantly faster than conventional one-character-at-a-time algorithms, but it does rely on b being small enough to fit in an int (hence the 4 character chunks).
#include <stdio.h>
#include <string.h>
int main(void) {
char as[]="123123123123126";
int l = strlen(as);
int rem;
int lm = l % 4; // the size of the initial chunk (after which we work in multiples of 4)
char *ap=as; // a pointer to keep track of "where we are in the string"
int b=123; // the divisor
int a;
sscanf(ap, "%4d", &a);
while(lm++ < 4) a /= 10;
// printf("initial a is %d\n", a);
rem = a % b;
for(ap = as + (l%4); ap < as + l; ap += 4) {
// printf("remainder = %d\n", rem);
sscanf(ap, "%4d", &a);
// printf("a is now %d\n", a);
rem = (a + 10000*rem) %b;
}
printf("remainder is %d\n", rem);
return 0;
}
Output:
remainder is 3
This needs some cleaning up but I hope you get the idea.
I have to input a number n, an a digit and a b digit and output the number n with all the a digits in it replaced by a b one. For example:
Input:
n = 1561525
a = 5
b = 9
Output:
n = 1961929
Should be recursive ! I didn't post any code as I've done it in a non-recursive way but apparently it's not even close to what I need.
Thanks for the help !
Check this, it works but maybe it is to much C
int convert(int num, int a, int b)
{
if( num )
{
int res = convert(num/10,a,b);
int t = num%10;
res *=10;
t = t == a ? b:t;
res = res + t;
return res;
}
return 0;
}
Divide by 10 the initial number, until nothing left of it, and then construct it again replacing a with b.
To make things easier, you can convert the number into a string (a char[] in C++). Then, it's a simple matter of iterating over it and checking at each step if the number we want to replace was found in the current position. For a possible solution, here's an implementation of the algorithm in Python - one of the nice things of the language is that it reads almost as pseudocode, and it should be relatively simple to port to C++:
def aux(n, a, b, i):
if i == len(n):
return ''
elif n[i] == a:
return b + aux(n, a, b, i+1)
else:
return n[i] + aux(n, a, b, i+1)
def change(n, a, b):
return int(aux(str(n), str(a), str(b), 0))
It works as expected:
change(1561525, 5, 9)
=> 1961929
So the easiest and safest way I can think of, is by using std::replace:
int replace(int num, int d1, int d2) {
string s = std::to_string(num); // convert to string
std::replace( s.begin(), s.end(), d1+'0', d2+'0'); // call std::replace
return atoi( s.c_str() ); // return the int
}
Now if you really have to use recursion (there is no need for it here), here's one possible solution:
using std::string;
// recursive function, accepts a string, current index, c2 replaces c1
string replace_rec (string s, unsigned index, char c1, char c2) {
// check if the it's still a valid index
if (index < s.size()) {
// if this is a char to be converted, do so
if (s[index] == c1)
s[index] = c2;
// call itself but with an updated string and incremented index
replace_rec(s, index+1, c1, c2);
}
// the last call will result in the string with all chars checked. return it
return s;
}
// call this function with input, the num to be replaced and what with
int replace(int num, int d1, int d2) {
string s = std::to_string(num); // convert to string
// convert the result back to int and return it.
return atoi( replace_rec(s, 0, d1+'0', d2+'0').c_str() );
}
In any case, you can call your replace() function like this:
int main(){
cout << replace (4578, 4, 9); // output: 9578
cin.get();
}