Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок+ 1
hey guys, I've been trying to work out the formula 'v=I*r'. But whenever I run the program and input values for I and r, it doesn't give the right answer. This is the code #include <iostream> using namespace std; int main() { int i,r; int v = i*r; cout<<"what is the value of i?\n"; cin>>i; cout<<"what is the value of r?\n"; cin>>r; cout<<"voltage ="<<v<<endl; return 0; } p/s: I'm new to programming
8 ответов
+ 4
When you declare int V, you are setting its value to (I * R), which is fine. Problem is, at this point int I and R have no value.
Set V to (I * R) after you have taken inputs for I and R, just like how Avinash Singh has demonstrated.
Some improvements I can suggest is not using int for those three values. Use a float or even a double. As a scientific equation, a lot of the time you will see decimals in place of I and R (and in turn, V). Additionally, in your example, int V is unnecessary, as you could always do:
cout << "V = " << I * R;
+ 3
If you want the multiplication of i and r... Then try this..
#include <iostream>
using namespace std;
int main() {
int i,r;
int v;
cout<<"what is the value of i?\n";
cin>>i;
cout<<"what is the value of r?\n";
cin>>r;
v=i*r;
cout<<"voltage ="<<v<<endl;
return 0;
}
+ 3
at the time of declaring v v is set to I times r. but at that time I and r has no value so declare v at the last
+ 2
Post your code here so we can help.
Are you using 'int' for I and R by any chance?
+ 2
wow thanks guys. Really helpful.
+ 2
in the earlier code snippet, you have initialized v as
v = I*r .
but as of that moment there is no value for i or r (since the cin function, which is used to input and assign data is called later)
now, when the cin statements are executed the values of I and r are assigned to them respectively.
next, when v is called in the cout statement the system assigns a random value (aka garbage value) to v as it does not go back to the assignment statement ie
int v= I*r
thus in a way the relation between v,i and r does not exist.
provide the relation between v,i,r after the cin statements and you're good to go.
hope it helped. :)
+ 1
thanks Avinash. I made the necessary changes and it worked. can you explain why my first code didn't work?
+ 1
Well you see.. When you initialized 'v' you made it equal to i*r.
Now at this point value of 'i' and 'r' isnt what you inputed.
It is some garbage value.. Now if multiply now you will get unexpected no.
Once you input i and r. Suppose you put i=3 and r=4.
So now v = i*r; // gives you 12...