我在编程任务时遇到了问题。我需要计算并联和串联电路的总电阻值。我有串联电路的功能,但我的问题是,当我尝试计算并联电路的总电阻时,我的返回值为1。我怎么能解决任何建议,这并行电路
// project.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
void menu()
{
cout <<"\t\t\tLab 2 Menu Driven Algorithms" << endl;
cout <<"\t\t Calculating Parallel and Series Resistance" << endl;
cout <<"1)\tSeries" << endl;
cout <<"2)\tParallel" << endl;
cout <<"3)\tQuit" << endl;
}
int series(int& num, int& sum)
{
int answer;
num = 0;
sum = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
sum = sum + answer;
num++;
}
while(answer != 0);
return sum;
}
double parallel (int& num, double& sum)
{
double answer;
num = 0;
sum = 0.0;
int counter = 0;
do
{
cout << "Enter Resistor " << num+1 << " value, 0 to calculate: ";
cin >> answer;
cout << endl;
counter++;
sum = (1/answer) + sum;
cout << sum << endl;
num++;
}
while(answer != 0);
return sum;
}
int main()
{
char choice;
int num = 0;
int sum = 0;
double sum2 = 0.0;
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
while (choice != '3' && choice != 'q' && choice != 'Q')
{
switch(choice)
{
case '1': cout << "Calculating Series Resistance" << endl;
cout << "The series resistance for the " << num-1 << " resistors is: " << series(num, sum) << " Ohms\n";
system("pause");
break;
case '2': cout << "Calculating Parallel Resistance" << endl;
cout << "The parallel resistance for the " << num-1 << " resistors is: " << parallel(num, sum2) << " Ohms\n";
system("pause");
break;
default: break;
}
system("cls");
menu();
cout <<"\n\nPlease enter a value from the menu: ";
cin >> choice;
cout << endl;
}
system("pause");
return 0;
}
你期待什么?当您输入'0'作为'answer',然后将'1/answer'加到'sum',**当然**将会是无限的。 – us2012 2013-02-18 20:00:51
请摆脱[系统(“暂停”)](http://www.gidnetwork.com/b-61.html)。我差点跑过程序在我的一台机器上测试它,并且该机器上的“暂停”命令暂停了我的核反应堆上的冷却系统。 – 2013-02-18 20:02:31
@DavidSchwartz哦,废话,对我来说已经太迟了。 – 2013-02-18 20:03:47