(3)From Nurse to C# Developer -- Programming Basics: Operators and Logic Judgment

(3)From Nurse to C# Developer -- Programming Basics: Operators and Logic Judgment

As a nurse, I resolutely crossed over into C# programming. Here I share the content of the third day of learning, covering core knowledge such as type conversion, operators, and logical judgment.

Last updated 2/25/2025 9:38 PM
勇敢的天使
11 min read
Category
Sharing
Topic
From Nurse to C# Developer
Tags
.NET C# Career Change to Development Programming

Today is my third day learning programming. As a nurse transitioning into programming, I was pleasantly surprised to find that the logical thinking in programming shares many similarities with clinical thinking in nursing. In nursing, we need rigorous assessment, precise judgment, and standardized operating procedures—these qualities are equally important in the programming world. Today's study gave me a deeper understanding of the basics of C#.

1. Type Conversion (Convert)

In medical information systems, data type conversion is a very common operation. Just as we need to unify units in clinical work (e.g., converting pounds to kilograms), programming often requires converting between different data types.

If two types are compatible, we can use implicit or explicit type conversion. But for incompatible types (such as string to int, or string to double), we need to use the conversion factory Convert.

It is important to note: when using Convert for type conversion, the data must be "reasonable." Just as the data input in a hospital must be accurate, the data being converted must be valid.

// Convert temperature data from string to double
string temperature = "37.2";
double tempValue = Convert.ToDouble(temperature);

// Convert blood pressure value from string to int
string systolicPressure = "120";
int systolic = Convert.ToInt32(systolicPressure);

// Convert bed number from string to int
string bedNumber = "205";
int bedNo = Convert.ToInt32(bedNumber);

2. Arithmetic Operators: ++ and --

In C#, the ++ and -- operators seem simple, but special attention is needed when using them. They come in two forms: prefix (n) and postfix (n), with subtle differences in effect.

Just as the order of administering medication to a patient affects the outcome in nursing, the position of these operators in an expression also impacts the final calculation result:

// Counting ward rounds
int roundCount = 10;
int result1 = 5 + ++roundCount; // Prefix: increment roundCount first, then use it
// roundCount becomes 11, result1 is 16

int visitCount = 10;
int result2 = 5 + visitCount++; // Postfix: use the original value first, then increment
// visitCount becomes 11, result2 is 15

// In medicine inventory management
int medicineStock = 100;
int currentStock = --medicineStock; // Decrement first, then assign
// Both medicineStock and currentStock are 99

int supplyStock = 100;
int oldStock = supplyStock--; // Assign first, then decrement
// supplyStock becomes 99, but oldStock remains 100

3. Relational Operators and Boolean Types

Relational operators (>, <, >=, <=, ==, !=) are widely used in medical practice. They are similar to the various judgments we make in clinical work: Is the body temperature normal? Is the blood pressure too high? Is the heart rate within a safe range?

The boolean (bool) type in C# has only two values: true and false. This is similar to many judgments in clinical settings, such as whether a patient has specific symptoms or requires special care.

// Body temperature monitoring
double bodyTemp = 37.5;
bool hasFever = bodyTemp >= 37.3; // Determine if fever is present

// Heart rate monitoring
int heartRate = 75;
bool isNormal = heartRate >= 60 && heartRate <= 100; // Determine if heart rate is normal

// Blood pressure monitoring
int systolic = 135;
int diastolic = 85;
bool isHypertension = systolic > 140 || diastolic > 90;

4. Logical Operators

Logical operators (&&, ||, !) play an important role in medical diagnosis and nursing decisions. They are like the thought process during clinical assessment:

  1. && (Logical AND): All conditions must be true, like determining whether a patient is suitable for discharge—multiple indicators must be normal.
  2. || (Logical OR): Only one condition needs to be true, like determining whether emergency treatment is needed—any dangerous indicator requires immediate attention.
  3. ! (Logical NOT): Reverses the result, like determining whether a patient is unsuitable for a certain treatment.
// 1. Logical AND (&&) Example: Determine if the patient can have surgery
double bodyTemp = 36.8;
int heartRate = 72;
int bloodSugar = 5;
bool canSurgery = (bodyTemp <= 37.2) && (heartRate < 100) && (bloodSugar < 6.1);
Console.WriteLine("Can have surgery: " + canSurgery);

// 2. Logical OR (||) Example: Determine if emergency medical intervention is needed
int systolic = 180;        // Systolic pressure
int diastolic = 95;        // Diastolic pressure
double oxygenLevel = 92;   // Blood oxygen level
bool needEmergencyCare = (systolic >= 180) || (diastolic >= 120) || (oxygenLevel < 93);
Console.WriteLine("Need emergency care: " + needEmergencyCare);

// 3. Logical NOT (!) Example: Determine if a patient is unsuitable for a certain test
bool hasAllergy = true;    // Whether there is an allergy history
bool isPregnant = false;   // Whether pregnant
bool canDoCtScan = !(hasAllergy || isPregnant);  // Reverse the condition unsuitable for CT scan
Console.WriteLine("Can perform CT scan: " + canDoCtScan);

// Combined usage example: Determine if transfer to ICU is needed
int respiratoryRate = 25;  // Respiratory rate
bool hasShock = true;      // Whether in shock
bool isStable = false;     // Whether condition is stable
bool transferToICU = (respiratoryRate > 30 || hasShock) && !isStable;
Console.WriteLine("Need transfer to ICU: " + transferToICU);

Through these examples, we can see the practical application of logical operators in medical decision-making. Combined use of these operators can help us build complex judgment conditions, just like in clinical work where we consider multiple factors to make decisions.

It is worth noting:

  • The && operator: if the first condition is false, subsequent conditions will not be evaluated.
  • The || operator: if the first condition is true, subsequent conditions will not be evaluated.
  • The ! operator can be combined with other logical operators to change the overall judgment result.

5. Compound Assignment Operators

Compound assignment operators (+=, -=, *=, /=, %=) make code more concise. These operators are especially useful in medical data processing:

// Medicine inventory management
int medicineStock = 100;
medicineStock += 50;    // Restock 50, equivalent to medicineStock = medicineStock + 50
Console.WriteLine($"Current stock: {medicineStock}");  // Output 150

// Calculate cumulative medication dosage (unit: ml)
double totalDosage = 500;
totalDosage -= 50;      // Use 50ml, equivalent to totalDosage = totalDosage - 50
Console.WriteLine($"Remaining dosage: {totalDosage}");    // Output 450

// Calculate bed occupancy rate
int totalBeds = 100;
int occupiedBeds = 80;
double occupancyRate = 0.8;
occupancyRate *= 100;   // Convert to percentage, equivalent to occupancyRate = occupancyRate * 100
Console.WriteLine($"Bed occupancy rate: {occupancyRate}%");  // Output 80%

// Calculate number of patients per nurse
int patientCount = 45;
int nurseCount = 6;
double patientsPerNurse = 45;
patientsPerNurse /= 6;  // Equivalent to patientsPerNurse = patientsPerNurse / 6
Console.WriteLine($"Patients per nurse: {patientsPerNurse}");  // Output 7.5

// Calculate remaining nurses after shift grouping
int remainingNurses = 15;
remainingNurses %= 4;   // Calculate remainder after grouping, equivalent to remainingNurses = remainingNurses % 4
Console.WriteLine($"Remaining nurses after grouping: {remainingNurses}");  // Output 3

Advantages of compound assignment operators:

  1. Code is more concise and readable
  2. Reduces repeated writing of variable names
  3. Especially convenient for cumulative or subtractive operations
  4. Very practical for quickly updating medical data

6. Sequential Structure

The sequential structure is the most basic program structure: the program starts from the Main function and executes from top to bottom in the order the code is written. This is similar to performing nursing operations, where we must strictly follow the standard sequence of steps.

1. Basic Sequential Structure

// Patient admission registration process
Console.WriteLine("Please enter patient name:");
string patientName = Console.ReadLine();

Console.WriteLine("Please enter patient age:");
int patientAge = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Please enter patient temperature:");
double temperature = Convert.ToDouble(Console.ReadLine());

// Display patient information in order
Console.WriteLine("Patient information summary:");
Console.WriteLine($"Name: {patientName}");
Console.WriteLine($"Age: {patientAge}");
Console.WriteLine($"Temperature: {temperature}");

2. Branching Structure: if, if-else

Branching structures are like our clinical decision paths, executing different operations based on different conditions:

// Body temperature monitoring and handling process
Console.WriteLine("Please enter patient temperature:");
double bodyTemp = Convert.ToDouble(Console.ReadLine());

if (bodyTemp >= 39.0)
{
    Console.WriteLine("1. Notify the doctor immediately");
    Console.WriteLine("2. Apply physical cooling");
    Console.WriteLine("3. Monitor vital signs closely");
}
else if (bodyTemp >= 37.3)
{
    Console.WriteLine("1. Continue monitoring temperature changes");
    Console.WriteLine("2. Measure temperature every hour");
}
else
{
    Console.WriteLine("Temperature normal, continue routine care");
}

3. Selection Structure: if-else if, switch-case

Used when multiple condition judgments are needed, e.g., deciding treatment plans based on various patient indicators:

// Using if-else if for triage
Console.WriteLine("Please enter patient pain level (0-10):");
int painLevel = Convert.ToInt32(Console.ReadLine());

if (painLevel >= 8)
{
    Console.WriteLine("Enter emergency channel immediately");
}
else if (painLevel >= 5)
{
    Console.WriteLine("Priority treatment");
}
else if (painLevel >= 3)
{
    Console.WriteLine("Outpatient visit");
}
else
{
    Console.WriteLine("Observation advised, seek medical attention if necessary");
}

// Using switch-case for test result classification
Console.WriteLine("Please enter test result level (A/B/C/D):");
string resultLevel = Console.ReadLine().ToUpper();

switch (resultLevel)
{
    case "A":
        Console.WriteLine("Test results normal");
        break;
    case "B":
        Console.WriteLine("Mild abnormality, need re-test");
        break;
    case "C":
        Console.WriteLine("Moderate abnormality, need further examination");
        break;
    case "D":
        Console.WriteLine("Severe abnormality, need immediate action");
        break;
    default:
        Console.WriteLine("Invalid level input");
        break;
}

4. Importance of Program Structure

Just as in medical work we need to follow standardized nursing procedures, program structure must be clear and orderly:

  1. Sequential structure ensures the program executes in the correct steps
  2. Branching structures help us handle different situations
  3. Selection structures make complex condition judgments clearer
  4. Good program structure improves code readability and maintainability

In medical information systems, proper use of these program structures can help us:

  • Standardize medical processes
  • Reduce medical errors
  • Improve work efficiency
  • Ensure patient safety

Learning Reflections

Today's study deepened my understanding of programming. I find that many concepts in programming have counterparts in nursing work:

  1. Type conversion is like unifying the units of various test indicators
  2. Operators help us perform precise medical data calculations
  3. Conditional judgments are strikingly similar to the decision-making process in clinical pathways
  4. Logical operators mirror our thought process during nursing assessment

These similarities not only make learning easier for me but also fill me with confidence for the future. I believe my nursing background will not be a barrier to learning programming but will become my advantage. In the wave of medical informatization, professionals who understand both healthcare and programming will play an important role.

Although the transition path is full of challenges, I believe that through continuous learning and practice, I will master this knowledge and contribute to the cause of medical informatization.

Tomorrow I will continue to delve into other C# knowledge. Let's look forward to the next share!

Keep Exploring

Related Reading

More Articles