Write a program Write a C program to accept the
height of a person in centimeter and categorize the
person according to their height.
Use height less than 150 means dwarf, equals 150
means average height and greater than or equal
165 means tall. Otherwise, it shall print “abnormal
height". Use (a) a "nested-if" statement;
Using nested if we can't use if else
You could use a series of if statements, like this:
if (height < 150) {
printf("dwarf");
}
else if (height == 150) {
printf("average height");
}
else if (height >= 165) {
printf("tall");
}
else {
printf("abnormal height");
}
Related
I have the following code, which does not look very nice. What methods could I use to make it look better?
Imagine that there are a lot of IF ELSE statements. As an example, I would like to distinguish whether the left is smaller or larger than the right. And more distances are added.
(It's about a robot that is supposed to detect obstacles in front of it.)
distance1 = left_LOX.distance();
distance2 = middle_LOX.distance();
distance3 = right_LOX.distance();
if (distance1 < 100 || distance2 < 100 || distance3 < 100)
distance_case = 1;
else if (distance1 < 300 || distance2 < 300 || distance3 < 300)
distance_case = 2;
else
distance_case = 3;
// Abfragen für die Automatik
switch (distance_case)
{
case 1:
target = 0;
robot.Stop();
delay(2000);
break;
case 2:
target = 4000;
robot.Forward();
break;
case 3:
target = 6000;
robot.Forward();
break;
}
An idea on how to make it better would be nice.
If you have a lot of distances (hundreds, thousand), it's easier to group all the distances together in a container such as vector first, and then use standard algorithms. E.g. something like this:
This is assuming you have the C++ std library available on the esp32 platform/compiler you are using - it should be possible at least up to C++11 - see e.g. https://medium.com/geekculture/modern-c-with-esp32-dcd3918dd978.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// Just an example vector initialisation - replace this with the required x_Lox.distance() calls.
std::vector<int> distances = {300, 500, 500, 200, 100 };
const auto min = *std::min_element(distances.begin(), distances.end());
std::cout << "Min distance: " << min;
return 0;
}
Once you have the minimum distance, you can run through the various cases for handling. This is based on the assumption that you are only interested in the shortest distance to choose your robot's action. If you have more complex logic, the code also gets more complex.
you can use if ... else if ... else block directly if the distance_case does not have long term use. It unnecessarily introduces new variables which has no purpose. Or define an enum if you see, in long term, there will many such cases. Reader can also quickly make sense of the values.
You can add if it looks better for you.
distance_case = (distance1 < 100 || distance2 < 100 || distance3 < 100) +
(distance1 < 300 || distance2 < 300 || distance3 < 300) +
(distance1 >= 300 || distance2 >= 300 || distance3 >= 300);
dmin= min(left_LOX.distance(), middle_LOX.distance(), right_LOX.distance());
if (dmin < 100)
{
target = 0;
robot.Stop();
delay(2000);
}
else if (dmin < 300)
{
target = 4000;
robot.Forward();
}
else
{
target = 6000;
robot.Forward();
}
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))
I am using a custom game engine created by one of my lecturers.
I have 4 inputs that the user can have for a pong game. These inputs work as intended however as soon as the sprite (paddle for pong) touches either the top or the bottom they get stuck there and are unable to move. Adding an else statement saying w_keypress = false; doesn't work.
if (w_keypress)
{
if (player_one->yPos() >= 0 && player_one->yPos() + player_one->height() <= game_height)
{
yspeed_player_one = -500;
s_keypress = false;
y_pos_player_one += yspeed_player_one * (game_time.delta.count() / 1000.f);
player_one->yPos(y_pos_player_one);
std::cout << "keypress w" << std::endl;
}
}
EDIT: The problem can easily be fixed by setting the y value to a y value that doesn't make the sprite interfere with the top or the bottom of the screen.
e.g.
if (player_one-yPos() > game_height)
{
player_one->yPos(game_height - (player_one->height() / 2)
}
else if (player_one->yPos() < 0)
{
player_one->yPos(0 + (player_one->height() / 2)
}
This code detects if the player has gone off the top or the bottom of the screen and then moves the player half of its height down or up depending on which y value you are.
Let's take a closer look at
if (player_one->yPos() >= 0 && player_one->yPos() + player_one->height() <= game_height)
{
yspeed_player_one = -500;
s_keypress = false;
y_pos_player_one += yspeed_player_one * (game_time.delta.count() / 1000.f);
player_one->yPos(y_pos_player_one);
}
bounds check position. If in bounds,
Update position by adding current velocity
Else
Do nothing
The problem is step 1.1 is too naive. If your sprite is zipping along toward a wall at sufficient speed, it can enter or completely pass through the wall as soon as you update its position. The next test of the bounds will trap the sprite because it is out of bounds.
Eg: Sprite is at 1000. Its height is 50 and its velocity per tick is 50. The wall is at 1080.
Step 1 tests 1000 + 50 <= 1080. This is true, so step 1.1 updates the position: 1000 + 50 = 1050. The sprite now occupies 1050 to 1099 and is inside the wall.
On the next button press, Step 1 tests 1050 + 50 <= 1080. This is false, so 2.1 is executed and the sprite does not move.
The test for collision with the wall is effectively performed after the sprite's gone out of bounds and by then it is too late.
You want a function that does something like
TYPE clamp_move(TYPE max_move,
TYPE distance_to_wall)
{
if (max_move < distance_to_wall)
{
max_move = distance_to_wall;
}
return max_move;
}
to prevent over shooting the bounds. Note this is pretty much std::min, so use std::min.
You wind up with
deltapos = std::min(yspeed_player_one * (game_time.delta.count() / 1000.f),
player_one->yPos());
y_pos_player_one -= deltapos;
or
deltapos = std::min(yspeed_player_one * (game_time.delta.count() / 1000.f),
game_height - (player_one->yPos() + player_one->height()));
y_pos_player_one += deltapos;
depending on which way the sprite is moving. Or by catching the overshoot and clamping before the next test.
y_pos_player_one += yspeed_player_one * (game_time.delta.count() / 1000.f);
if (y_pos_player_one <0)
{
y_pos_player_one = 0;
}
else if (y_pos_player_one > game_height - player_one->height())
{
y_pos_player_one = game_height - player_one->height();
}
whichever is easier on your brain.
I'm trying out some sample code for a bigger project, and I'm having trouble getting my rectangle to bounce between two lines.
function draw() {
print(frameCount)
background(255)
var x = 150 + frameCount;
rect(x,200,15,15);
line(150,0,150,400);
line(250,0,250,400);
if (x >= 250) {
background(255)
x = 350-frameCount;
rect(x,200,15,15);
line(250,0,250,400);
line(150,0,150,400);
} if (x <= 145) {
background(255)
x = 145 + (frameCount % 100);
rect(x,200,15,15);
line(250,0,250,400);
line(150,0,150,400);
}
}
I'm getting the feeling that after the first instance, it's disregarding the original if statement, which dictates a bounce to the left. I'm really not sure what's going wrong, and any help would be appreciated.
You probably just want to store the current position and speed in a set of variables, and then move the rectangle based on those. Here's an example:
var x = 0;
var speed = 1;
function draw(){
x += speed;
if(x < 0 || x > width){
speed *= -1;
}
background(64);
line(x, 0, x, height);
}
I've written a tutorial on this available here. That's for regular Processing, but the ideas are the same in P5.js.
I'm using a for loop to iterate through some arrays I've created representing regions that the mouse can hover over. Then when the loop confirms the mouse is in a region it saves the iteration variable to a public variable that is used later in the main function to highlight the region the mouse is over. The problem is that the for loop is not giving the right value for the first iteration through.
{
//mouse offsets
int x = 0, y = 0;
//if mouse moves
if (event.type == SDL_MOUSEMOTION)
{
//get the mouse co-ords
x = event.motion.x;
y = event.motion.y;
for (int grid = 0; grid <= sizeof(grid_region); grid++)
{
if ((x > grid_region[grid].x) && (x < grid_region[grid].x + GRID_WIDTH) && (y > grid_region[grid].y) && (y < grid_region[grid].y + GRID_HEIGHT))
{
//set highlight region
highlight = grid;
}
}
}
}
grid_region is is made via "int grid_region[9];" and the strange part is that when I later do a print statement to see what "highlight" is when it's in grid_region[0] is prints 72. How is it possible that the iteration variable becomes 72 at any point in the loop??? Any help here? I later use highlight to apply a sprite in the grid_region and it's being applied incorrectly so this is a problem.
sizeof(grid_region) is the size in multiples of char, not the number of elements.
That is, it is sizeof(int) * 9, not nine, and apparently your int is 8 chars wide since you ended up at 72.
You can loop to < sizeof(grid_region) / sizeof(grid_region[0]) or, better, step into the 21st century and use std::vector, or std::array if your compiler is hip enough.