c++ using user input data for multiple functions - c++

Hi i am looking to write a program for a arbitrary triangle.
Whilst i have completed the first part of my task which is to find if the triangle is either true or false. i want to be able to use the data inputted by the user to calculate the perimeter then eventually the area of the triangle.
But when the perimeter is calculated it is rather huge number.
This is my code so far.#include "stdafx.h"
#include "math.h"
enter code here
// ConsoleApplication6.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "math.h"
/* enter three variables a, b ,c to create a triangle*/
int main()
{
double a; /*insert dimensions of side a*/
double b; /*insert dimensions of side b*/
double c; /*insert dimensions of side c*/
double p; /*variable for the perimeter of a triangle*/
double s; /*variable for the area of a triangle*/
/* Get the user to enter the dimensions of a*/
printf_s("enter the dimensions of a: ");
scanf_s("%d", &a);
/* Get the user to enter the dimensions of b*/
printf_s("enter the dimensions of b: ");
scanf_s("%d", &b);
/* Get the user to enter the dimensions of c*/
printf_s("enter the dimensions of c: ");
scanf_s("%d", &c);
/* Conditions of a triangle*/
if ("a + b > c && a + c > b && b + c > a")
printf_s("True\n"); /* Display True if able to make a triangle*/
else printf_s("False\n"); /* Display false if unable to make a triangle*/
double p = a + b + c;
/*Scan user input data a, b, c*/
scanf_s("%d", &a, "%d", &b, "%d", &c);
/*output total perimeter*/
printf_s("The perimeter of the triangle is: ""%d, p");
return 0;
}

The problems is that all %d should be replaced by %lf in order to match the type double.
And also remove the line scanf_s("%d", &a, "%d", &b, "%d", &c);, once you scan once, you cannot scan again to get the same value.

Related

Fill missing user input with zeros

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);
}

How to compute sum, average and product of three numbers using different functions

I need to create a program that accepts 3 numbers and find the sum, average and product. I only need to use main(), get_ABC(), compute() and display() functions. I did it right but im not getting the right output about my mathematical operations.
#include<conio.h>
#include<iostream.h>
float get_A(float A)
{
cout<<"Enter First Number: ";
cin>>A;
return(A);
}
float get_B(float B)
{
cout<<"Enter Second Number: ";
cin>>B;
return(B);
}
float get_C(float C)
{
cout<<"Enter Third Number: ";
cin>>C;
return(C);
}
float compute_sum(float A,float B,float C)
{
float sum;
sum = A + B + C;
return(sum);
}
float compute_ave(float A,float B,float C)
{
float ave;
ave = (A + B + C) / 3;
return (ave);
}
float compute_prod(float A,float B,float C)
{
float prod;
prod = A * B * C;
return(prod);
}
void display(float sum,float ave,float prod)
{
cout<<"The sum of three numbers is "<<sum<<".\n";
cout<<"The average of three numbers is "<<ave<<".\n";
cout<<"The product of three numbers is "<<prod<<".";
}
float main()
{
float A,B,C;
float sum;
float ave;
float pro;
clrscr();
get_A(A);
get_B(B);
get_C(C);
sum = compute_sum(A,B,C);
ave = compute_ave(A,B,C);
pro = compute_prod(A,B,C);
display(sum,ave,pro);
getch();
return(0);
}
This is the output.
Enter First Number: 1
Enter Second Number: 2
Enter Third Number: 3
The sum of three numbers is 0.
The average of three numbers is 0.
The product of three numbers is 0.
I really need help. My prof give me this problem without teaching how to code, so i only come up with basics, i really gave up and end up here. You can change, add or replace the codes(with basic codes) if you want and i'll appreciate it.
Change this:
get_A(A);
get_B(B);
get_C(C);
to this:
A = get_A(A);
B = get_B(B);
C = get_C(C);
so that you use the return values of your functions.
Moreover, main() should return an int, not a float.
Furthermore, initialize your variables when you declare them, so that you avoid "is used uninitialized in this function" warnings.

Euler method in c++

The following code uses Euler's Method to approximate a value of y(x). My code currently accepts the endpoints a and b as user input and values for values for alpha which is the initial condition and the step size value which is h. Given my code I can now approximate a value of y, say y(8) given the initial condition y(0)=6.
However I have a small mistake in my code and I am not quite sure how to fix it and am looking for help. Right now my code does not check to ensure that the right endpoint b is an integer multiple of the stepsize h. Due to this the final approximation may not be for f(b) but for f(c) where c is the closest integer multiple of h to b. I am looking for some help on how to fix this, Thanks!
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double dydx (double x, double y)
{
double f = y*(2-y)/(x+3);
return f;
}
int main()
{
double a,b,alpha,h,z;
cout<<"\nEnter the value of endpoint a: \n";
cin>>a;
cout<<"\nEnter the value of endpoint b: \n";
cin>>b;
cout<<"\nEnter the y value of the initial condition: \n";
cin>>alpha;
cout<<"\nEnter the stepsize, h: \n";
cin>>h;
cout<<"\n";
while((b-a)>0.0000001)
{
z=alpha+(h*dydx(a,alpha));
cout<<"z("<<a<<")="<<z<<endl;
alpha=z;
a=a+h;
}
cout<<"\nThe approximate solution of y("<<b<<") is "<<z<<"."<<endl;
return 0;
}
You can calculate step size h from number of steps n:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double dydx (double x, double y)
{
double f = y*(2-y)/(x+3);
return f;
}
int main()
{
double a,b,alpha,h,z;
cout<<"\nEnter the value of endpoint a: \n";
cin>>a;
cout<<"\nEnter the value of endpoint b: \n";
cin>>b;
cout<<"\nEnter the y value of the initial condition: \n";
cin>>alpha;
/*
* Obtains step size from number on steps
* h = 0.1 for [a; b] = [0; 8] can be given by n = 80
*/
int n = 0;
cout<<"\nEnter the number of steps, n: \n";
cin>>n;
h = (b - a) / n;
//------
cout<<"\n";
//-- Replaced 0.0000001 by h / 2.0 --
while((b-a)> h / 2.0)
{
z=alpha+(h*dydx(a,alpha));
alpha=z;
a=a+h;
/*
* z - function value in next point,
* so to output correct point a need to be incremented before this.
*/
cout<<"z("<<a<<")="<<z<<endl;
}
cout<<"\nThe approximate solution of y("<<b<<") is "<<z<<"."<<endl;
return 0;
}
Insert this instead of h input.

creat random number in double format, eclipse stop working

generate random number 0-1, when I type the input number less than 4, the code works fine. However when the input number above 4, the eclipse stop working. what's wrong with my code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double ran(double x0, double x1){
return x0+(x1-x0)*rand()/((double)RAND_MAX);
}
int main(void) {
int a,i;
double *b;
printf("input the size\n");
scanf("%d", &a);
b=(double*)malloc(sizeof(int)*a);
srand((unsigned)time(NULL));
for(i=0;i<a;i++)
{
b[i]=ran(0,1);
printf("\n %f", b[i]);
}
free (b);
return 1;
}
A double is bigger than an integer. A double is eight bytes, while an integer is 4 bytes.
You should replace
b = (double*)malloc(sizeof(int)*a);
with
b = (double*)malloc(sizeof(double)*a);
or even better (thaks to Lưu Vĩnh Phúc)
b = malloc(a * sizeof b[0]);

Declarations, Definitions and Calls

i need to gain a better understanding of function definition, declarations and proper calls using this program. I really need the understanding of how to use them. Could you show me the proper way to write this program with all three correct and explained?
#include <stdio.h>
#include <math.h>
quad_equation(float a, float b, float c);
int main()
{
float a, b, c, determinant, r1,r2;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0) { r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else (determinant<0);
{
printf("Both roots are complex");
}
return 0;
I just solved this exact question here : (I guess this is a part of an assignment )
https://stackoverflow.com/a/19826495/1253932
Also looking at your code .. you never use the function quad equation .. also you haven't defined the type of the function ( int/void/float/char) etc.
For ease: ( here is the entire code ) -- ask me if you don't understand anything
#include <stdio.h>
#include <math.h>
// function declarations
void twoRoots (float a,float b,float delta);
void oneRoot (float a,float b,float delta);
int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;
// float solution;
printf("Input coefficient a.\n");
scanf("%f", &a);
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c);
delta = (float)(b*b) - (float)(4.0 * a * c);
printf("delta = %0.2f\n",delta);
if (delta > 0){
twoRoots(a,b,delta);
}else if (delta == 0) {
oneRoot(a,b,delta);
}else if (delta < 0.0){
printf("There are no real roots\n");
}
return 0;
}
void twoRoots (float a,float b,float delta)
{
float xOne;
float xTwo;
float deltaRoot;
printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", xOne);
printf("%.2f", xTwo);
}
void oneRoot(float a,float b,float delta)
{
float xOne;
// float xTwo;
// float deltaRoot;
printf("There is exactly one distinct root\n");
xOne = -b / (2*a);
printf("%.2f", xOne);
}
EDIT:
A slightly more optimized and better functioning code that I made from the above mentioned code:
http://pastebin.com/GS65PvH6
Edit2:
From your comments you try to do this:
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
This will fail if you input something like this: 121
Beacuse scanf will read the whole 121 into a and it will have nothing for b,c ( rather it will put \n(enter) into b and undefined into c )
So use the scanf the way I have used it in my code
OK - this is full of problems! I attempt to point them out, and show what "better" looks like. I hope this helps.
quad_equation(float a, float b, float c);
This is probably intended to be a "function prototype". A prototype tells the compiler "I am going to use this function later, and this is how it needs to be called, and the type it returns". You did not specify a return type; probably you want to use int to say whether you found roots or not, and print out the result in the function. Better would be to pass space for two return values as a parameter:
int quad_equation(float a, float b, float c, float* x1, float* x2);
Now we can use the main program to get input/output, and let the function solve the problem:
int main(void) {
{
float a, b, c, r1, r2;
int n;
// here you get the inputs; that seems OK
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a,&b,&c);
// now you have to "call your function"
// note that I make sure to follow the prototype: I assign the return value to an int
// and I pass five parameters: the coefficients a, b, c and the address of two variables
// x1 and x2. These addresses will be where the function puts the roots
n = quad_equation(a, b, c, &r1, &r2);
// when the function returns, I can print the results:
printf("There are %d roots:\n", n);
// based on the value of n, I change what I want to print out:
if (n == 2) printf(" %f and ", r1); // when there are two roots I print "root 1 and"
if (n > 0) printf("%f\n", r2); // when there is at least one root, I print it
// note that if n == 0, I would skip both print statements
// and all you would have gotten was "There are 0 roots" in the output
}
int quad_equation(float a, float b, float c, float* x1, float* x2) {
// function that computes roots of quadratic equation
// and returns result in x1 and x2
// it returns the number of roots as the return value of the function
float determinant;
determinant=b*b-4*a*c;
if (determinant>0)
{
*x1 = (-b+sqrt(determinant))/(2*a);
*x2= (-b-sqrt(determinant))/(2*a);
return 2;
}
if (determinant==0) {
*x1 = *x2 = -b/(2*a);
return 1;
}
return 0;
}