I have a little problem with check for multiplicity for 3. It says that my arr must be integer, but in objective I need to have a float massive. How to make this check "arr[i] % 3 == 0" for float numbers.
thanks.
#include <iostream>
#include <cmath>
using namespace std;
float minElement(float arr[], int length) {
float minElement = arr[0];
for (int i = 0; i < length; i++)
{
if (minElement > arr[i])
minElement = arr[i];
}
return minElement;
}
float multiplyArr(float arr[], int length) {
float multiply = 1;
for (int i = 0; i < length; i++)
{
if (arr[i] != 0 && arr[i] % 3 == 0)
multiply *= arr[i];
}
return multiply;
}
int main()
{
float length;
cout << "Enter integer value: ";
cin >> length;
float* p_darr = new float[length];
cout << "Enter values: " << endl;
for (int i = 0; i < length; i++) {
cin >> p_darr[i];
}
cout << "Max. element: " << minElement(p_darr, length) << endl;
cout << "Multiply: " << multiplyArr(p_darr, length) << endl;
delete[] p_darr;
return 0;
}
Assuming
float massive
to mean "large value". You cannot perform this operation, as it would be meaningless. Comments (and other answers) will suggest fmod. I'll advise against.
If I give you the value 3.6x10^12 and ask you what's the remainder after division by 3, you can't give me a meaningful answer.
3600000000000 % 3 is 0. 3600000000001 % 1 is 1. 3600000000002 % 2 is 2.
But all three values are 3.6x10^12.
If you need integer modulo values, it typically means you need integer precision. Float values won't offer it.
Rather, you should read your input as a string, parse it character by character, and compute the modulo so far. This is a typical first assignment in a computer theory class (as I used to TA).
Related
Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}
I need help with a c++ program that:
"Prompts users for N integers and determines/displays the integer
with the highest and lowest value – use separate functions to return the highest and lowest value. N is a random number from 5 to 10 (both inclusive)."
This is what I have so far:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum(int);
void largestNum(int);
int smallNum;
int largeNum;
int randomNum;
int num[10];
int main()
{
smallestNum(smallNum);
largestNum(largeNum);
system("pause");
return 0;
}
void randNumGenerator()
{
srand(time(0));
randomNum = 5 + (rand() % 10);
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
}
void smallestNum(int smallNum)
{
randNumGenerator();
smallNum = num[randomNum];
for (int i = 0; randomNum <= i; i++)
if (num[randomNum] < smallNum)
{
smallNum = num[randomNum];
}
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(int largeNum)
{
randNumGenerator();
largeNum = num[randomNum];
for (int i = 0; i <= i; i++)
if (num[randomNum] > largeNum)
{
largeNum = num[randomNum];
}
cout << "The largest integer is: " << largeNum << endl;
}
But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!
There are several issues:
First, with randomNum = 5 + (rand() % 10);, you generate random numbers between 5 and 14, inclusive, which may exceed int num[10]. Use randomNum = 5 + (rand() % 6); to get values between 5..10.
In your loops for (int i = 0; randomNum <= i; i++), with random <= i, you exceed array bounds since randomNum can go up to 10 and num[10] is already out of bounds for int num[10]. Write ... randomNum < i instead.
The same problem with smallNum = num[randomNum]; it exceeds array bounds; use smallNum = num[0] instead.
BTW: I'd interpret your assignment such that you enter the numbers once and then find the smallest and largest number in two different functions. In your code, you enter the numbers twice...
And: It's useless passing the smallNum into the function that overrides its value then. I'd rather use a function like int smallestNum() { ... return smallNum; } instead.
Hope it helps.
Try this,
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum();
void largestNum();
void getInput();
int num[11];
int length;
int main(){
smallestNum();
largestNum();
return 0;
}
void randNumGenerator(){
int from = 5;
int to = 10;
srand(time(0));
length = from + (rand() % (to - from));
}
void getInput(){
for (int x = 1; x <= length; x++) {
cout << "Enter the integer num[" << x << "]: ";
cin >> num[x];
}
}
void smallestNum(){
cout << "Finding smallest integer\n";
randNumGenerator();
getInput();
int smallNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] < smallNum)
smallNum = num[i];
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(){
cout << "Finding largest integer\n";
randNumGenerator();
getInput();
int largeNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] > largeNum)
largeNum = num[i];
cout << "The largest integer is: " << largeNum << endl;
}
With above code, I hope you will find your mistakes on your own :)
In addition to the first answer, this loop makes no sense:
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
randomNum is the same every loop, so you just keep overwriting the same array value.
And...
for (int i = 0; i <= i; i++)
This loop is wrong. You are checking i <= i which will always evaluate true.
I was making an app that calculates the mean, median, and range of any integers, but I ran into the issue: Vector subscript out of range. I've looked at some other posts about this, and still haven't been able to fix it.
Here's my code:
#include <iostream>
#include <Algorithm>
#include <Windows.h>
#include <vector>
using namespace std;
int main() {
//Variables
int sze;
int mraw = 0;
double mean;
double median;
double range;
int fullnum = 0;
int lastnum = 1;
vector<int> med;
cout << "How many numbers do you have? ";
cin >> sze;
int *arr = new int[sze];
for (int i = 0; i < sze; i++) {
med.push_back(arr[i]);
}
//Getting numbers
for (int i = 0; i < sze, i++;) {
system("cls");
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
//Mean
for (int i = 0; i < sze; i++){
fullnum += arr[i];
}
mean = fullnum / sze;
//Median
sort(med.begin(), med.end());
int mvs = sze;
while (med.size() >= 2) {
med.erase(med.begin());
med.erase(med.begin() + med.size() - 1);
mvs--;
}
if (mvs == 2) {
mraw = med[1] + med[2];
median = mraw / 2;
}
else {
median = mvs;
}
//Range
vector<int> rnge;
for (int i = 0; i < sze; i++) {
rnge.push_back(arr[i]);
lastnum++;
}
sort(rnge.begin(), rnge.end());
int bigsmall[2];
bigsmall[1] = rnge[1];
bigsmall[2] = rnge[lastnum];
range = bigsmall[2] - bigsmall[1];
//Outputs
cout << "Mean: " << mean << "\nMedian: " << median << "\nRange: " << range;
system("cls");
return 0;
}
You have what would be an off-by-one error if lastnum was initialized to 0.
When rnge is empty, presumably lastnum is 0. This means access rnge[lastnum] is in error, as rnge is empty.
Applying an inductive argument shows that lastnum is the count of number of elements, and not the index of the last element. Thus, rnge[lastnum] is always out of range.
In actuality, you have initialized lastnum to 1, so your bug is actually off-by-two.
I have this program that finds the largest integer in an array using recursion, but it keeps returning the last number entered no matter what the value instead of the largest number. How do i fix this?
#include <iostream>
using namespace std;
int maximum(int digits[], int size, int largest, int i);
void main()
{
const int size = 3;
int digits[size];
int n = 0, x = 0;
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[n];
}
cout << "\nThe largest digit is, " << maximum(digits, size, 0, 0) << ", thank you!\n";
cout << endl;
}
int maximum(int digits[], int size, int largest, int i)
{
if ( i < size )
{
if ( largest < digits[i])
largest = digits[i];
maximum( digits, size, largest, i + 1);
}
return largest;
}
First use the index variable properly in main()
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[a];//-->Use the index varible correctly.
}
int maximum(int digits[], int size, int largest, int i)
{
if(i==size-1)
return digits[i]; //The base case is specified here.
if ( i < size )
{
int temp= maximum( digits, size, largest, i + 1);
if ( digits[i] < temp)
largest =temp;
else
largest=digits[i];
}
return largest;
}
Please check out the changes. Carefully read the code. You will understand your mistakes.
When designing recursion think of few things first-
The base condition. (This stops the recursion).
The recursive step. (Where you will calculate something based on previous calculation)
Combine step- You have to combine them (value at this stage and value got from recusive step) to get the correct answer. This step is not required in some cases.
It should be return maximum( digits, size, largest, i + 1);
Live example.
int biggestOne(int integerArray[], int lengthOfArray, int max)
{
if (lengthOfArray==0) return max;
if (max < integerArray[lengthOfArray-1]) max = integerArray[lengthOfArray-1];
return biggestOne(integerArray,lengthOfArray-1,max);
}
int main()
{
int array[] = {7,2,9,10,1};
int arrSize = sizeof(array)/sizeof(array[0]); //returns length of the array
cout <<"Biggest number in the array: " << biggestOne(array,arrSize,0) << endl;
return 0;
}
We had a project that asked us to Write a program that allows a user to enter a series of numbers "read numbers into an array for further processing, user signals that they are finished by entering a negative number (negative not used in calculations), after all numbers have been read in do the following, sum up the #'s entered, count the #'s entered, find min/max # entered, compute average, then output them on the screen. So the working version of this that I made looks like so
/* Reads data into array.
paramater a = the array to fill
paramater a_capacity = maximum size
paramater a_size = filled with size of a after reading input. */
void read_data(double a[], int a_capacity, int& a_size)
{
a_size = 0;
bool computation = true;
while (computation)
{
double x;
cin >> x;
if (x < 0)
computation = false;
else if (a_size == a_capacity)
{
cout << "Extra data ignored\n";
computation = false;
}
else
{
a[a_size] = x;
a_size++;
}
}
}
/* computes the maximum value in array
paramater a = the array
Paramater a_size = the number of values in a */
double largest_value(const double a[], int a_size)
{
if(a_size < 0)
return 0;
double maximum = a[0];
for(int i = 1; i < a_size; i++)
if (a[i] > maximum)
maximum = a[i];
return maximum;
}
/* computes the minimum value in array */
double smallest_value(const double a[], int a_size)
{
if(a_size < 0)
return 0;
double minimum = a[0];
for(int i = 1; i < a_size; i++)
if (a[i] < minimum)
minimum = a[i];
return minimum;
}
//computes the sum of the numbers entered
double sum_value(const double a [], int a_size)
{
if (a_size < 0)
return 0;
double sum = 0;
for(int i = 0; i < a_size; i++)
sum = sum + a[i];
return sum;
}
//keeps running count of numbers entered
double count_value(const double a[], int a_size)
{
if (a_size < 0)
return 0;
int count = 0;
for(int i = 1; i <= a_size; i++)
count = i;
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int INPUT_CAPACITY = 100;
double user_input[INPUT_CAPACITY];
int input_size = 0;
double average = 0;
cout << "Enter numbers. Input negative to quit.:\n";
read_data(user_input, INPUT_CAPACITY, input_size);
double max_output = largest_value(user_input, input_size);
cout << "The maximum value entered was " << max_output << "\n";
double min_output = smallest_value(user_input, input_size);
cout << "The lowest value entered was " << min_output << "\n";
double sum_output = sum_value(user_input, input_size);
cout << "The sum of the value's entered is " << sum_output << "\n";
double count_output = count_value(user_input, input_size);
cout << "You entered " << count_output << " numbers." << "\n";
cout << "The average of your numbers is " << sum_output / count_output << "\n";
string str;
getline(cin,str);
getline(cin,str);
return 0;
}
That went fine, the problem I am having now is part 2. Where we are to "copy the array to another and shift an array by N elements". I'm not sure where to begin on either of these. I've looked up a few resources on copying array's but I was not sure how to implement them in the current code I have finished, especially when it comes to shifting. If anyone has any thoughts, ideas, or resources that can help me on the right path it would be greatly appreciated. I should point out as well, that I am a beginner (and this is a beginners class) so this assignment might not be the 'optimal' way things could be done, but instead incorporates what we have learned if that makes sense.
for(int i = 0; i < n; ++i){
int j = (i - k)%n;
b[i] = a[j];
}
Check it. I'm not sure
If this works you could improve it to
for(int i = 0; i < n; ++i)
b[i] = a[(i - k)%n];//here can be (i +/- k) it depends which direction u would shift
If you only want to copy the array into another array and shift them
ex : input = 1, 2, 3, 4, 5; output = 3, 4, 5, 1, 2
The cumbersome solution is
//no template or unsafe void* since you are a beginner
int* copy_to(int *begin, int *end, int *result)
{
while(begin != end){
*result = *begin;
++result; ++begin;
}
return result;
}
int main()
{
int input[] = {1, 2, 3, 4, 5};
size_t const size = sizeof(input) / sizeof(int);
size_t const begin = 2;
int output[size] = {0}; //0, 0, 0, 0, 0
int *result = copy_to(input + begin, input + size - begin, output); //3, 4, 5, 0, 0
copy_to(input, input + begin, result); //3, 4, 5, 1, 2
return 0;
}
How could the stl algorithms set help us?
read_data remain as the same one you provided
#include <algorithm> //std::minmax_element, std::rotate_copy
#include <iostream>
#include <iterator> //for std::begin()
#include <numeric> //for std::accumulate()
#include <string>
#include <vector>
int main(int argc, char *argv[]) //don't use _tmain, they are unportable
{
const int INPUT_CAPACITY = 100;
double user_input[INPUT_CAPACITY];
int input_size = 0;
double average = 0;
cout << "Enter numbers. Input negative to quit.:\n";
read_data(user_input, INPUT_CAPACITY, input_size);
auto const min_max = std::minmax_element (user_input, user_input + input_size); //only valid for c++11
std::cout << "The maximum value entered was " << min_max.second << "\n";
std::cout << "The lowest value entered was " << min_max.first << "\n";
double sum_output = std::accumulate(user_input, user_input + input_size, 0);
cout << "The sum of the value's entered is " << sum_output << "\n";
//I don't know the meaning of you count_value, why don't just output input_size?
double count_output = count_value(user_input, input_size);
cout << "You entered " << count_output << " numbers." << "\n";
cout << "The average of your numbers is " << sum_output / count_output << "\n";
int shift;
std::cout<<"How many positions do you want to shift?"<<std::endl;
std::cin>>shift;
std::vector<int> shift_array(input_size);
std::rotate_copy(user_input, user_input + shift, user_input + input_size, std::begin(shift_array));
//don't know what are they for?
std::string str;
std::getline(std::cin,str);
std::getline(std::cin,str);
return 0;
}
if your compiler do not support c++11 features yet
std::minmax_element could replace by
std::min_element and std::max_element
std::begin() can replace by shift_array.begin()
I don't know what is the teaching style of your class, in my humble opinion, beginners should
start with those higher level components provided by c++ like vector, string, algorithms
and so on.I suppose your teachers are teaching you that way and you are allowed to use the
algorithms and containers come with c++(Let us beg that your class are not teaching you "c with classes" and say something like "OOP is the best thing in the world").
ps : You could use vector to replace the raw array if you like