I'm trying to compute the formula "V / I = R" in my program by asking the user to input values for V and I. Unfortunately my program does not compile and I'm not sure why.
#include <iostream>
using namespace std;
int main()
{
int V, I, R;
cout << "Please enter the voltage: " << endl;
cin >> V;
cout << "Please enter the curruent: " << endl;
cin >> I;
V / I = R;
cin >> R;
cout << "The value of the resistor is: " << R << endl;
system("PAUSE");
}
C++ is not a system to solve linear equation, you must tell it what to do.
You need to replace:
V / I = R;
cin >> R;
with
R = V / I;
The knowledge you used, to flip the equation around, stays with you. The compiler needs instructions. Also note the = is not the symbol for equality. It is the symbol for assignment. It evaluates the right-hand side and assigns it to the variable on the left-hand side. Some other language write it := to make this clearer.
You should also use float instead of int if you want to be able to get fractional answers, like 0.5.
Related
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 4 years ago.
Improve this question
Just begin to learn C++, and the code below can't return the right value. I can't find out where is wrong, need some help here, thank you!
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M << endl;
return 0;
}
cin operation is when you retrieve the value:
you need to get it before any process:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
Just for the fun of it, and for education's sake. If you want to emulate declarative programming in C++, to define the relationship between variables and "get the updated value" afterwards, you can get by with a lambda.
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
auto M = [&] { return 1.0f * CM / CM2M + (CM % CM2M) * 0.01f; };
cout << "Enter the height in CM: ";
cin >> CM;
cout << "Your in M is " << M() << endl;
return 0;
}
It's cheating really, since M() invokes the lambda, thus making sure the arithmetic is done after the value is known. Writing the operations in the correct sequence is far clearer. C++ also allows you to declare variables right at the first point of use, so you don't need to declare all your variables ahead of time, you can execute code before the declaration is needed. So you'd do something like this:
const int CM2M = 100;
int main()
{
using namespace std;
int CM;
cout << "Enter the height in CM: ";
cin >> CM;
float M = 1.0f * CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
return 0;
}
I added the artificial 1.0f to make sure it doesn't do integer division, which was another bug in your code.
Put the "float M=..." line after the "cin >>CM;" line. Now you are trying to compute the number of meters before the number of centimeters is even entered, so of course the result is random.
Because CM is only declared and used in the equation before the user has a chance to initialize it.
The current program flow is like this:
CM is declared
M is calculated using the CM value (whatever that is at this moment)
The user enters value for CM
The user sees the result of the conversion (the value for M) however it is already calculated and the user input is not actually
used.
To fix the program move the calculation after the user input:
cout << "Enter the height in CM: ";
cin >> CM;
float M = CM / CM2M + (CM % CM2M) * 0.01f;
cout << "Your in M is " << M << endl;
#include <iostream>
#include <vector>
using namespace std;
typedef vector<double> vec; //vec now acts like a datatype
int main()
{
vec powers; //stores powers of x in the objective function
vec coefficients; //stores coefficients of x in the objective function
double pow;
double coeff = 0;
cout << "Enter powers of x present in the objective function and enter any character to stop" << endl;
cout << "REMEMBER TO ENTER 0 IF CONSTANT EXISTS!" << endl;
while (cin >> pow)
powers.push_back(pow); //Working fine
cout << endl;
for (vec::iterator iter_p = powers.begin(); iter_p != powers.end(); iter_p++)
{
double coeff;
cout << "Enter coefficient of the (x^" << *iter_p << ") term: ";
cin >> coeff; //THIS IS NOT EXECUTING
coefficients.push_back(coeff); //NOT WORKING EITHER
}
cout << endl;
return 0;
system("pause");
}
I want to input powers of a polynomial equation along with coefficients. I am able to store the powers in a vector. But in the for loop I am using to input coefficients, cin is simply not executing. I would be much obliged if someone could out what exactly is causing cin statement to be skipped.
The issue here is you tell the user to enter a character to end
while (cin >> pow)
powers.push_back(pow);
While that works, it also puts cin in an error state and leaves the character in the buffer. You need to clear that error state and get rid of the character left in the input. You would do that by adding
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
after the while loop. clear clears the errors and the call to ignore gets rid of any characters left in the input.
This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}
I've been assigned a problem that asks us to solve a 2 equation system using an array and a pointer to that array. It's sort of a linear algebra way of going about it, with x_1 = (DE-BF)/(AD - BC) and x_2 = (AF - CE)/(AD - BC). The system is Ax_1 + Bx_2 = C and Dx_1 + Ex_2 = F. My code compiles fine but spits out garbage. Can anyone help me? I'm sure it's an error with my pointers but I don't know how to correct it. Much thanks in advance.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(){
double A,B,C,D,E,F;
cout << "Please enter a value for A: " << endl;
cin >> A;
cout << "Please enter a value for B: " << endl;
cin >> B;
cout << "Please enter a value for C: " << endl;
cin >> C;
cout << "Please enter a value for D: " << endl;
cin >> D;
cout << "Please enter a value for E: " << endl;
cin >> E;
cout << "Please enter a value for F: " << endl;
cin >> F;
double paramarray[6] = {A,B,C,D,E,F};
double* p;
p = ¶marray[6];
double x1 = (p[3]*p[4] - p[1]*p[5])/(p[0]*p[3] - p[1]*p[2]);
double x2 = (p[0]*p[5] - p[2]*p[4])/(p[0]*p[3] - p[1]*p[2]);
cout << "X_1 = " << x1 << endl;
cout << "X_2 = " << x2 << endl;
int f;
cin >> f;
return 0;
}
p = ¶marray[6];
This is the problem. This means you are assigning the address of paramarray[6] to p. paramarray[6] is not defined and you are trying to access out of bounds array.
Try changing it to
p = paramarray;
Also, it will be better if you first check for zero denominator and update your equation accordingly.
Your pointer should be initialized with the base of the array which is the address of the first element. And in your program you are initializing it to a address out of bounds which is the index 6 where the last index of the array is 5 itself.
An array of size six means the first index is 0 and the last index is 5.
so change your line:
p = ¶marray[6];
to
p = paramarray; //or p=¶marray[0].Both are same here
This above line will store the address of the first element in pointer p.
I am trying to create an exponent function and it does not seem to work as expected. Sorry if I don't understand some basic things, I'm just learning bits and pieces off the internet.
float x;
float y;
float z;
int h;
int j;
float exponent (float a, float b)
{
float r;
while(b > 1)
{
r = a * a;
b = b - 1;
}
return (r);
}
^Snippet of the function with variables.
cout << "EXPONENT MODE\n\n";
cout << "Please enter a number: ";
cin >> x; system("CLS");
cout << "Please enter another number as the exponent for the first: ";
cin >> y;
z = exponent(x, y);
cout << "Calculating the answer, please wait";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << "\n\nYour answer is : ";
cout << r;
Sleep(5000);
system("CLS");
cout << "Would you like to calculate another set of numbers? (yes = 1, no = 2) : ";
cin >> h;
system("CLS");
^Part I want to execute on the console.(Just code)
Basically, I want the user to input 2 numbers, the first(x) being the base number, the second(y) being the exponent. The program should input x as a and y as b and run the function. What happened: Input 1: 5, Input 2: 3, Expected: 125, Received: 25. I'm thinking about changing the while to (b > 0). If you guys could help that would be great!.
(Also don't judge me on the system("CLS") in the code)
It's fairly simple, you're printing the wrong variable.
cout << "\n\nYour answer is : ";
cout << r;
r is a local member variable of exponent. In the scope of main, the result of exponent was actually stored in a variable called z
z = exponent(x, y);
The fix is just to change your answer printing code to
cout << "\n\nYour answer is : ";
cout << z;
For your own benefit, you might want to try giving your variables more meaningful names and only declaring them in scopes where they are actually needed. I don't see you using r elsewhere in main, did you make it global in an attempt to try and make the r in exponent accessible there too?
I dont under stand what #kfsone is talking about.
but in the loop r is set as a*a everytime, isn't this why you are getting the square instead of exponent ? I think what you really want to do is this:
r=1
while( ...
r *= a;// note to accumulate result on r
b --;