This is the problem my professor wants me to solve with a C++ program...
To design a square timber column in a structure, three formulas must
be satisfied:
column pcture-1.jpg
Buckling load: The maximum load the column can hold for buckling which needs to be greater than the expected load on the column.
Maximum load = (.3 x E x Area) / (Length / Width)2
Compressive stress: The maximum load the column can hold for compression which needs to be greater than the expected load on the
column.
Maximum load = Area x Maximum compressive strength
Slenderness limit: Ratio of Length to Width of the column must be less than or equal to 50
(Length / Width)<= 50
where: E = the modulus of elasticity = 1,700,000 lb/in2
Area = width x width = the cross sectional area in square inches
Maximum compressive strength = 445 lb/in2 for a Douglas Fir tree.
Write a program that uses these three formulas to give an initial
design to a structural engineer. Assume the columns to be used are
square in cross-section and are available in intervals of 2 inches
(i.e. 2 by 2, 4 by 4, 6 by 6 and so on). Have the output look like
the following:
Please enter the expected load on the column in pounds--> 9000
Please enter the length of the column in inches--> 120
... .Testing a beam with Area of 2.0 by 2.0 inches – Failed the tests
... .Testing a beam with Area of 4.0 by 4.0 inches – Failed the tests
... .Testing a beam with Area of 6.0 by 6.0 inches – Passed the 3 required tests
For a load of 9000.0 pounds and a length of 120.0 inches, recommended
square beam has sides of 6.0 inches The timber cost will be $ 216
You must write a function for each of the three tests using call by
value. Your main program will call these three functions in order to
solve the problem. Test your program for the above input and for the
case of 18000 lb load and column length 72 inches. If the price of
the timber is 0.05 $/in3 report the difference between the cost of
the timbers.
This is the program I wrote, but it forms an endless loop; I am not sure how to fix it, and solve the problem my professor wants me to.
#include <iostream>
#include <fstream> // outfile
#include <cmath>
#define E 1700000 // lb/in^3 (E is modulus of elasticity)
#define MCS 445 // lb/in^3 (MCS is maximum compressive strength)
using namespace std;
bool buckling_load();
bool compressive_stress();
bool slenderness_limit();
//1.0 declare variables
float expected_load;
float column_length;
bool tests_passed = false;
float column_width = 2;
int main() {
ofstream outfile;
outfile.open("outfile.txt");
//2.0 get user input
cout << "Please enter the expected load on the column (lbs), and the
column length (in) ->" << endl;
cin >> expected_load >> column_length;
//3.0 test the different widths
while (!tests_passed) {
if (buckling_load() && compressive_stress() && slenderness_limit()){
tests_passed = true;
cout << column_width << " by "<< column_width << " Passed the three required tests";
}
else {
cout << column_width << " by "<< column_width << " Failed the three required tests";
column_width +=2;
}
}
}
//4.0 define functions
bool buckling_load(){
if (expected_load < ((0.3 * E * pow(column_width, 2)) / pow(column_length / column_width, 2))){
return true;
}
else{
return false;
}
}
bool compressive_stress(){
if (expected_load < ((pow(column_width,2)) * MCS)){
return true;
}
else{
return false;
}
}
bool slenderness_limit(){
if(50 <= (column_length/column_width)){
return true;
}
else {
return false;
}
}
This condition
Slenderness limit: Ratio of Length to Width of the column must be less
than or equal to 50
does not correspond to your source:
bool slenderness_limit(){
if(50 <= (column_length/column_width)){
return true;
}
else {
return false;
}
}
The condition should be reversed:
if(50 >= (column_length/column_width))
Related
How to solve the following errors in this code in visual studio 2022 version: expected an identifier on line 33
identifier "otherUser" is undefined on line 33 expected a']' on line 33 identifier "ratings" is undefined on line 38 language feature 'structured bindings' requires compiler flag 'std:c++17' on line 33
#include <iostream>
#include <map>
#include <vector>
#include <cmath>
#include <xlnt/xlnt.hpp>
// Define a type alias for a map that maps a user ID to a vector of ratings
using UserRatings = std::map<int, std::vector<double>>;
// Define a function to calculate the cosine similarity between two users
double cosineSimilarity(const std::vector<double>& user1, const std::vector<double>& user2) {
// Initialize variables to store the dot product and the magnitudes of the vectors
double dotProduct = 0.0;
double magnitude1 = 0.0;
double magnitude2 = 0.0;
// Calculate the dot product and magnitudes of the vectors
for (size_t i = 0; i < user1.size(); i++) {
dotProduct += user1[i] * user2[i];
magnitude1 += user1[i] * user1[i];
magnitude2 += user2[i] * user2[i];
}
// Calculate and return the cosine similarity
return dotProduct / (sqrt(magnitude1) * sqrt(magnitude2));
}
// Define a function to predict the rating of a movie for a given user
double predictRating(const UserRatings& userRatings, int user, int movie) {
// Initialize variables to store the predicted rating and the sum of the similarities
double prediction = 0.0;
double sumSimilarities = 0.0;
// Iterate over all users in the userRatings map
for (const auto& [otherUser, ratings] : userRatings) {
// Skip the current user
if (otherUser == user) continue;
// Calculate the similarity between the current user and the other user
double similarity = cosineSimilarity(userRatings.at(user), ratings);
// If the similarity is positive, add it to the sum of similarities and
// add the other user's rating for the movie to the prediction
if (similarity > 0) {
sumSimilarities += similarity;
prediction += similarity * ratings[movie];
}
}
// Return the predicted rating for the movie
return prediction / sumSimilarities;
}
int main() {
// Load the data from an Excel file
xlnt::workbook workbook;
workbook.load("ratings.xlsx");
xlnt::worksheet sheet = workbook.active_sheet();
// Create a map of user ratings
UserRatings userRatings;
for (auto row : sheet.rows()) {
int user = row[0].value<int>();
std::vector<double> ratings;
for (auto cell : row) {
if (cell.column() == 1) continue;
ratings.push_back(cell.value<double>());
}
userRatings[user] = ratings;
}
// Predict the rating of movie 3 for user 1
double prediction = predictRating(userRatings, 1, 3);
std::cout << "Predicted rating for movie 3 by user 1: " << prediction << std::endl;
return 0;
}
I want to implement dataset from an excel file
In your code we could see that the code lacks the definition of the following variables, you need to define them according to your requirements.
feature 'structured bindings' requires compiler flag 'std:c++17' on
line 33
For this error, you need to right click on the project and select project properties, then set C++ Language Standard to c++17.
Part of a program that I'm working on implements a function that takes in the package weight as an argument and calculates the shipping cost based on that weight. The criteria for the cost/lb is as follows:
Package Weight Cost
-------------- ----
25 lbs & under $5.00 (flat rate)
26 - 50 lbs above rate + 0.10/lb over 25
50 + lbs above rate + 0.07/lb over 50
I used an if-if else-if to make the calculations, but feel like its a bit repetitive:
const int TIER_2_WEIGHT = 25;
const int TIER_3_WEIGHT = 50;
const float TIER_1_RATE = 5.00;
const float TIER_2_RATE = 0.10;
const float TIER_3_RATE = 0.07;
float shipPriceF;
if(shipWeightF <= TIER_2_WEIGHT)
{
shipPriceF = TIER_1_RATE;
}
else if(shipWeightF <= TIER_3_WEIGHT)
{
shipPriceF = ((shipWeightF - TIER_2_WEIGHT) * TIER_2_RATE) +
TIER_1_RATE;
}
else
{
shipPriceF = ((shipWeightF - TIER_3_WEIGHT) * TIER_3_RATE) +
((TIER_3_WEIGHT - TIER_2_WEIGHT) * TIER_2_RATE) +
TIER_1_RATE;
}
return shipPriceF;
So, the question is... is this the best way to accomplish this task, or should I be looking for a different solution?
First at all, you code looks clear and ok as it is.
Of course, you could deduplicate the redundant parts of the formulas by using a cumulative approach:
float shipPriceF = TIER_1_RATE; // to be paid anyway
if (shipWeightF > TIER_2_WEIGHT) // add the tier 2 if necessary
{
shipPriceF += (min(shipWeightF, TIER_3_WEIGHT) - TIER_2_WEIGHT) * TIER_2_RATE;
}
if(shipWeightF > TIER_3_WEIGHT) // add the tier 3 if really necessary
{
shipPriceF += (shipWeightF - TIER_3_WEIGHT) * TIER_3_RATE);
}
Well, this could even be simplified further:
float shipPriceF = TIER_1_RATE
+ max(min(shipWeightF,TIER_3_WEIGHT)-TIER_2_WEIGHT,0) * TIER_2_RATE
+ max(shipWeightF-TIER_3_WEIGHT,0) * TIER_3_RATE;
For 3 scales, it's probably ok with this synthetic formula. If you want more flexibility however, you could think of iterating throug a vector of rates instead of using constants. This would allow for a variable number of scales. If you're sure that the formula is always progressive (eg. "above + new unit price for what's exceding") use then the cumulative approach.
I think there are a lot of nearly identical lines in the code but not real duplicates. If you add more rates you can easily copy the wrong macro definitions or mix the values from the wrong rate.
My code itself removes the if/else replications and avoid the need of using the correct global definition. If you add a new rate to my code you simply add a raw to the table.
Only to give an idea what else can be done:
#include <iostream>
#include <functional>
#include <limits>
// first we define a entry of a table. This table contains the limit to which the ratio is valid and
// a function which calculates the price for that part of the weight.
struct RateTableEntry
{
double max;
std::function<double(double, double)> func;
};
// only to shrink the table width :-)
constexpr double MAX = std::numeric_limits<double>::max();
// and we define a table with the limits and the functions which calculates the price
RateTableEntry table[]=
{
// first is flate rate up to 25
{ 25, [](double , double )->double{ double ret= 5.00; return ret; }},
// next we have up to 50 the rate of 0.10 ( use min to get only the weight up to next limit
{ 50, [](double max, double weight)->double{ double ret= std::min(weight,max)*0.10; return ret; }},
// the same for next ratio. std::min not used, bedause it is the last entry
{ MAX, [](double , double weight)->double{ double ret= weight *0.07; return ret; }}
};
double CalcRate(double weight)
{
std::cout << "Price for " << weight;
double price = 0;
double offset = 0;
for ( auto& step: table )
{
// call each step, until there is no weight which must be calculated
price+=step.func(step.max- offset, weight);
// reduce the weight for that amount which allready is charged for
weight-=step.max-offset;
// make the table more readable, if not used this way, we have no max values but amount per step value
offset+=step.max;
if ( weight <= 0 ) break; // stop if all the weight was paid for
}
std::cout << " is " << price << std::endl;
return price;
}
int main()
{
CalcRate( 10 );
CalcRate( 26 );
CalcRate( 50 );
CalcRate( 51 );
CalcRate( 52 );
CalcRate( 53 );
}
If C++11 is not available, you also can use normal functions and function pointers instead of lambdas and std::function.
I need help with this question: A piece of wire is to be bent in the form of a rectangle to put around a picture frame. The length of the picture frame is 1.5 times the width. Write a program that prompts the user to input the length of the wire and the outputs the length and the width of the picture frame. I'm not sure if I should code something that has got to do with the perimeter.
I've tried to start it
#include <iostream>
using namespace std;
int main() {
double length;
double width;
cout << "Input the length of the wire:";
cin >> length;
cout << endl;
return 0;
}
Hint:
Well you know that the length of the wire. So let's call that L.
Width will be fW and length of frame will be fL.
Then you have:
2*fW + 2*fL = L.
fL = 1.5*fW
2*fW + 2*(1.5*fW) = L
L = 5*fW
fW = L/5.
So basically you know that the width of the frame will be length of wire divided by 5. And length will be 1.5 times that.
I am using the Xinput API, but I am having trouble with the following bit of code. My assumption is that the definition of R/LX and R/LY, should dynamically change as its called again and again, but the value for the position of the thumb stick is arbitrarily set to -13108, so the normalized magnitude of X and Y is -.707, and the normalized magnitude is ~.428. I keep trying to move the control stick but the values won't change. Any ideas? Am I misunderstanding the Xinput API? Does the struct controller state make sense? The code is below is just for the left stick, but the right stick is very similar.
#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE 7849
#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD 30
struct CONTROLLER_STATE
{
XINPUT_STATE state;
bool bConnected;
};
CONTROLLER_STATE g_Controllers[4];
while(1)
{
//...
XINPUT_STATE state = g_Controllers[1].state;
float LX = state.Gamepad.sThumbLX;
float LY = state.Gamepad.sThumbLY;
//determine how far the controller is pushed
float magnitude = sqrt(LX*LX + LY*LY);
//determine the direction the controller is pushed
float normalizedLX = LX / magnitude;
float normalizedLY = LY / magnitude;
cout << " Y " << LY << endl;
float normalizedMagnitude = 0;
//check if the controller is outside a circular dead zone
if (magnitude > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
{
//clip the magnitude at its expected maximum value
if (magnitude > 32767) magnitude = 32767;
//adjust magnitude relative to the end of the dead zone
magnitude -= XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
//optionally normalize the magnitude with respect to its expected range
//giving a magnitude value of 0.0 to 1.0
normalizedMagnitude = magnitude / (32767 - XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE);
cout << "normalizedMagnitude " << normalizedMagnitude;
}
else //if the controller is in the deadzone zero out the magnitude
{
magnitude = 0.0;
normalizedMagnitude = 0.0;
}
}
You have normalised a state, and it is rather empty. I would assume that you are atleast calling XInputGetState() in your bool function bConnected, however this would probably be called once and hence values would remain the same. Therefore, either in your main, or in your associated function displayed above, you should call the getstate function once, first line in the while loop, so as it runs, the state is updated continously.
I am currently working on a project. I need write a program that computes the perimeter and volume of 3 boxes. The height, width and depth of the boxes are 10, 20, 30, 40, 50, 60, 70, 80, 90. The first 3 elements represent the height, width and depth of the first box, respectively speaking. The second group of three represent the second box and the last three represent the last box (height, width, depth).
Now I need to put the 9 given values in array, which I have done. Then i need to use 2 independent functions to calculate the volume and perimeter and I need to use a loop to repeat the calculations for all 3 boxes. once the functions calculate the perimeter and volume, the 6 values (3 perimeters and 3 volumes) need to be placed in array, then displayed.
I initialized an Array and stored the 9 values in the code. I created two independant functions that will compute the perimeter and the volume. I used a loop so so that the perimeter and the volume will be computed for all three boxes. Now I am having trouble figuring out how to store the computed values into an array?
Here is my code:
#include<iostream>
using namespace std;
struct myArrayWrapper
{
int m_array[9];//Array for the 9 given values
int n_array[6];//Array for the 6 values we will be computing
};
int perimeter(myArrayWrapper a)//function to calculate the perimiter
{
int p;
int* A = a.m_array;
int* B = a.n_array;
for(int b = 0 && int a = 1 && int s = 0; a < 8 && b < 9; a+=3 && b+=3 && s+=2) {//for loop to calculate the perimeter of the 3 boxes
p = 2*A[a] + 2*A[b];
}
}
int volume(myArrayWrapper a)// function to calculate the volume
{
int v;
int* B = a.m_array;//pointer
for(int c = 0 && int d = 3 && int e = 6; c < 3; c+=3 && d+=3 && e+=3){
int v;
v = B[c]*B[d]*B[e];
}
}
int main()
{
myArrayWrapper obj;
obj.m_array[0] = 10;//height of box 1
obj.m_array[1] = 40;//height of box 2
obj.m_array[2] = 70;//height of box 3
obj.m_array[3] = 20;//width of box 1
obj.m_array[4] = 50;//width of box 2
obj.m_array[5] = 80;//width of box 3
obj.m_array[6] = 30;//depth of box 1
obj.m_array[7] = 60;//depth of box 2
obj.m_array[8] = 90;//depth of box 3
for(int x = 0; x < 8; x++){//Loop that checks to make sure that the given dimensions are greater than 0
if(obj.m_array[x]>0)
cout << "Element number " << x << "is greater than 0" << endl;
else
cout << "The element is not greater than 0" << endl;
return 0;
}
perimeter(obj);
volume(obj);
}
What it sounds like you need to use is the return statement. This will allow your functions to actually return the value that they are calculating, so your perimeter function would look more like this:
int perimeter(myArrayWrapper a)//function to calculate the perimiter
{
int p;
/* your code */
p = 2*A[a] + 2*A[b];
return p;
}
This will return the integer value calculated for p, then in your main loop you can assigne the returned value to your wanted location in your array.
There is more information on the return statement here.
One other thing that may give you trouble that I noticed was that your return statement in your main function is going to be called on the first iteration of your for loop. When a return statement is called within a function, the function will actually stop running there and return that value, meaning your main function is stopping before it actually reaches the calls to your perimeter and volume functions.