Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Problem:
How many times does it take for one person to carry all items? Person can carry 'carryWeight' kg of weight each time.
My solution:
int main()
{
int a = 40; // 1st item weight
int b = 35; // 2nd item weight
int c = 20; // 3rd item weight
int maxItemWeight = a; // Max weight item.
int times; // Times to carry all the items
int carryWeight; //How much weight a person can carry at once
cin >> carryWeight;
if (maxItemWeight > carryWeight)
cout << "It's impossible to carry all the items " << endl;
else {
if((a + b + c) <= carryWeight)
times = 1;
else if ((a+b) <=carryWeight && (a+c) <=carryWeight && (b+c) <=carryWeight)
times = 2;
else
times = 3;
cout << "Times to carry all the items: " << carryWeight << endl;
}
return 0;
}
Solution is simple, but if you have to add more variables it gets complicated. Is it possible to use an array and some loop to get a solution for any number of variables?
It appears you are asking if you can use an array to allow for any number of "items" to be carried. The answer is yes:
std::vector<int> item_weights;
unsigned int item_count = 0;
std::cout << "Enter item count: ";
std::cin >> item_count; // I'll leave the error checking to you to implement
for (unsigned int i = 0; i < item_count; ++i)
{
std::cout << "Enter weight for item " << (i + 1) << ": ";
unsigned int w = 0;
std::cin >> w; // again error checking should be added
item_weights.push_back(w);
}
// insert code to retrieve maximum weight that can be carried here
unsigned int max_weight = std::max_element(item_weights.begin(), item_weights.end());
unsigned int total_weight = std::accumulate(item_weights.begin(), item_weights.end(), 0);
// insert your code to determine the number of times it would take to carry all items here
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
Im fairly new to C++ and im trying to convert an int "city.temp[4]" to a string and then adding that to an already existing string "city.name[4]" which would then sort the cities and their temperatures based on low to high. The user is the one to name all four cities and assign them a temperature. The bubbleSort is working fine sorting the temperatures by them self but im not sure how to get the cities to follow along with their respective temperatures
#include <iostream>
using namespace std;
class City{
public:
string name[4];
int temp[4];
};
int main() {
City city;
city.name[4];
city.temp[4];
cout << " Please Input the name of 4 different cities and their temperature\n\n\n";
for(int i=0; i < 4; i++){
cout << " Input the name and temperature of city (" << i+1 << "): "; getline(cin, city.name[i]); cout << " "; cin >> city.temp[i];
cin.ignore();
}
int length = 4;
for(int i = 0; i < length; i++){
for(int j = 0; j < length - 1; j++){
if(city.temp[j] > city.temp[j+1]){
int hold = city.temp[j];
city.temp[j] = city.temp[j+1];
city.temp[j+1] = hold;
}
}
}
for(int i = 0; i < length; i++)
cout << " " << city.temp[i] << " " << city.name[i] << "\n";
return 0;
}
The good solution is to have a City-class with a name and a temperature and swap cities based on the order of the temperature with std::sort.
The easy fix for now is to use std::swap to swap the temperatures and at the same time swap the names:
if(city.temp[j] > city.temp[j+1]){
std::swap(city.temp[j], city.temp[j+1]);
std::swap(city.name[j], city.name[j+1]);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I wrote code to evaluate the expression above. It executes, but I suspect that the expression is not evaluated correctly.
#include <iostream>
#include <math.h>
using namespace std;
int main(){
setlocale(0, "");
// Задание 1
cout << "Задание 1" << endl;
cout << "" << endl;
double m, x, k, k1, k2;
int n = 18;
cout << "Определите m: ";
cin >> m;
cout << "Определите x: "; // вероятно, в задании ошибка. Если не положу ничего в x - там будет
//единица, ответы будут примерно одинаковые.
cin >> x;
do // начало цикла do while
{
k2 = pow(x, 3*x+1);
k1 = k2 * (8*x);
k = k1 - 785;
}
while (n < m); // конец цикла do while
cout << "Результат вычисления, k = " << k << endl;
system("pause");
}
If you want to use a loop instead of calling std::pow, you have to fix its condition and iteration expression. The calculations inside the body are also different from the posted formula. Note the following changes:
double k = 1.0;
for (int i = n; i <= m; ++i)
{ // ^^^^^^^^^^^^^^^
k *= pow(x, 3.0 * x + 1.0) + 8.0 * x;
// ^^ ^^^
}
k -= 785.0; // <- This should be outside
Note that the body of the for loop doesn't depend on i, so that there are plenty of ways to refactor this code in more efficient ways.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I seem to be looping through my array wrong, I've got it set up to prompt the user for a list of numbers and I am supposed to be comparing it to another number that the user sets.
#include <iostream>
using namespace std;
bool chk = true;
int main() {
/*
Write a program that asks the user to type 10 integers of an array and an integer s.
Then search the value s from the array and display the value of s if it is found in
the array otherwise print sorry not found..
*/
int userArray[10], i, greater = 0;
int s;
cout << "Enter a check number: \n";
cin >> s;
if (chk = true) {
//prompt for array list
for (i = 0; i < 9; i++) {
if (i == 0) {
cout << "Enter ten numbers: " << "\n";
cin >> userArray[i];
}
else {
cin >> userArray[i];
}
chk = false;
}
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
//I was just using this to pause the console and let me inspect result
cin >> greater;
return 0;
}
}
}
I assume the following code is where the problem lies. The idea is i set s = 2 enter in a list of numbers and then compare to s and print s if there is a match if not I print No match found. When I enter in a number that i know matches s it seems to print the first number in the array, but i thought since I loop through the numbers one by one in the for loop that it should display when it reaches the right number not when it stops. Thanks in advance
//loop through the array
for (int i = 0; i <= 10; i++) {
if (s = userArray[i]) {
//for testing
cout << userArray[i];
//cout << s;
}
else {
cout << "No match found!";
}
You are using a single equals sign. This is setting s to userArray[i] so it always evaluates to true. For comparisons, use double equal signs, like this:
if (s == userArray[i]) {...}
Also, your return statement is inside your loop (credit to #UnholySheep).
you are comparing with a single assignment operator = you should be using the equal operator instead ==
if (s = userArray[i]) with in the for loop is one example.
you also doing the same mistake in
if (chk = true)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <iostream>
#include <string>
using namespace std;
bool custNum(char [], int);
int main()
{
const int size = 8;
char custmor[size];
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin.getline(custmor, size);
if(custNum(custmor, size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(char custNum[], int size)
{
int count;
for(count = 0; count<3; count++)
{
if(!isalpha(custNum[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
if(!isdigit(custNum[count]))
return false;
}
return true;
}
so I want to loop through a character array of 3 letters and 4 numbers like ABC1234, but I didn't get the condition of the second for loop (size - 1). How does it work every time it tests the condition?
Never use count as a loop variable. A good name for a loop variable is i.
Never declare variables away from their initialization. The above should be for( int i = 0; ... in both cases.
i < size - 1 is probably wrong. What you probably want is i < size.
Anyhow, it would help if you showed how size is declared, how it is initialized, etc. It would also help if you showed the exact text you are trying to parse. It would also help if you explained exactly what you expected to happen, and exactly what happened instead. I might amend my answer when you do that.
you read only amount of characters that size variable specify,
since then , Why custNum function would not return true for anything longer than size variable ? , Because it's not checking anything more than what size variable specify.
Below is the code you need
#include <iostream>
#include <string>
using namespace std;
bool custNum(string,unsigned int);
int main()
{
const unsigned int size = 8;
//char custmor[size];
string mystring;
cout << "Enter a customer number in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN = numbers): ";
cin >> mystring;
cout << mystring <<endl << " " << mystring.length() << endl;
// cin.getline(custmor, size);
if(custNum(mystring , size))
cout<<"That's a valid id number"<<endl;
else
cout<<"That's not a valid id number"<<endl;
return 0;
}
bool custNum(string s, unsigned int size)
{
unsigned int count;
if (s.length() != (size + 1))
return false;
for(count = 0; count<3; count++)
{
if(!isalpha(s[count]))
return false;
}
for(count = 3; count <size - 1; count++) //3<7 , 4
{
cout << s[count] <<endl;
if(!isdigit(s[count]))
return false;
}
return true;
}