Monday, July 27, 2009

C# problem?

I am trying to make a little resistor calculator, which could be used for example for working out what resistor is needed to wire to an LED inside a computer case. However, whenever I run the program it always gives me an answer which I know by working out manually is incorrect, and very far off. As you can probably tell, my programming is very basic and I do not have much experience at all with C#, but hopefully someone can point me in the right direction as to where I am going wrong.





#include %26lt;stdio.h%26gt;


#include %26lt;math.h%26gt;





int main()





{





float v1;





float v2;





float I;





float R = (v1 - v2) / I;





printf("Please enter the voltage of the source.\n");





scanf("%f",%26amp;v1);





printf("\n");





printf("Please enter the voltage that the object runs at.\n");





scanf("%f",%26amp;v2);





printf("\n");





printf("Please enter the current at which the object runs.\n");





scanf("%f",%26amp;I);





printf("The value of the resistor needed is %f Ohms", R);





printf("\n");





return 0;





}

C# problem?
First, this is C rather than C# (though if you're really a beginner, C# may be a bit easier and would have caught the problem here).





What's happening is that you are trying to compute R before the other values are input. In C, using an undefined variable doesn't give you a compiler error, but instead picks up left over garbage in memory and uses that. To get this working, edit the R calculation to just be the type declaration (float R;) and then move the text "R = (v1-v2)/l;" just before the line where you print the value.
Reply:Also, is there anything I can do so that when its prompts you to enter say the voltage of the source, after the blinking icon there is the unit (In this case volts or amps). Thanks for the help





lalilulelosamsung Report It

Reply:You can change how it prints using formatting in the printf statement:





printf( "The value of the resistor needed is %4.2f Ohms\n", R ); Report It

Reply:For your prompt question, I think you're asking how to do this:





Please enter the voltage of the source.


_ Volts





I have seen this done before with fancy formatting where you basically print the up arrow control character or backspace character. But I don't have any details. Report It



No comments:

Post a Comment