x 应该是 =28.24778761,但我得到 28

the x should be =28.24778761 but i get 28

本文关键字:24778761      更新时间:2023-10-16

我刚开始学习 c++

在这个程序中,我尝试两个根据电阻器的值对两个电阻器进行分类但是最后我无法正确打印出x,而只能打印出前面的部分,例如,我尝试了 R1=0 R2=50 R3=100 R4=60 V=9 n=4 第一个值=55 第二个=56 第三个=52 第四个=57 x 应该是 56*57/(56+57)=28.24778761 但我只得到 28 为什么?

#include <iostream>
using namespace std;
int main()
{
    int n;
    float V, TOTAL1, TOTAL2, y;
    int r1, r2, r3, r4, i;
    cout << "Give r1: "; // Ask for resistors.
    cin >> r1;
    cout << "Give r2: ";
    cin >> r2;
    cout << "Give r3: ";
    cin >> r3;
    cout << "Give r4: ";
    cin >> r4;
    cout << "Give voltage: ";
    cin >> V;
    cout << "Give number of resistors: ";
    cin >> n;
    int a, b; // Ccount the number on its category.
    int m;
    m = 0;
    a = 0;
    b = 0;
    y = 0;
    TOTAL2 = 0;
    for(i = 1; i < n + 1; i++)
    {
        y = TOTAL2 + y; // Calculate the as they are in series
        float value;
        m = m + 1;
        cout << "n Give resistance: ";
        cin >> value;
        if((value >= r1) && (value >= r2) && (value <= r3) && (value <= r4))
        {
            if(m % 2>0)
            {
                cout << "It belongs to the first";
                a = a + 1;
                TOTAL1 = value + TOTAL1; // If they are in the first category they are connected in series
            }
            else
            {
                cout << "It belongs to the second";
                b = b + 1;
                TOTAL2 = 1 / value;
            }
        }
        else if((value >= r1) && (value <= r2)){
            cout << "It belongs to the first";
            a = a + 1;
            TOTAL1 = value + TOTAL1;
        }
        else if((value >= r3) && (value <= r4)) {
            cout << "It belongs to the second";
            b = b + 1;
            TOTAL2 = 1 / value + 1 / TOTAL2;
        }
    }
    long double x;
    x = 1 / y;
    cout << "n The first category has: " << a;
    cout << "n The second category has: " << b;
    cout << "n The total resistance of the first category is: " << TOTAL1;
    cout << "n The total resistance of the second category is: " << x;
    return 0;
}

变量y仅在循环顶部更新,因此上次更新将丢失。所以y包含 1/28(第一个值),当你取它的倒数时,你得到的正好是 28。