Click here to Skip to main content
15,908,015 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi guys, I'm new to C#.
I'm not sure why my code doesn't want to run.
Once I start to run my code, nothing comes up on the cmd prompt.
It just shows a blank screen.

What I have tried:

I have to write a C# console program that converts temperature in degrees Celsius to degrees Fahrenheit.
Showing all values from –40 degrees Celsius to +40 degrees Celsius in steps of 5 degrees.

This is what I got so far:

C#
<pre>
using System;
namespace TemperatureConverter
{
    class Program
    {
        static void Main()
        {
            int c, f;
            for (c = -40; c <= 40; c =+ 5);
            f = 9 / 5 * c + 32;
            Console.WriteLine("c: {0}; f: {1}", c, f);
        }
    }
}


I don't know if my code is right or not.
Your assistance is much appreciated.
Posted
Updated 25-May-18 5:25am

1 solution

You've made quiet a few errors there:
C#
for (c = -40; c <= 40; c =+ 5);
The semicolon at the end will terminate the loop - so it will never do anything
inside the body. Remove the semicolon.
And the increment operator is wrong as well:
C#
c=+ 5
means "set c to 5", not "add 5 to c". You probably want
C#
c += 5

for (c = -40; c <= 40; c =+ 5);
f = 9 / 5 * c + 32;
Console.WriteLine("c: {0}; f: {1}", c, f);
If you want more than one statement inside your loop, you need a compound statement - which is a fancy way of saying "put curly brackets round them".
9 and 5 are integers, so 9 / 5 is also an integer: 1. You need floating point values: 9.0 and 5.0 instead.
There's one other problem as well: if you fix this and run this code in the debugger, you probably won't see anything as the command prompt will open, print and shut really quickly. Add
Console.ReadLine();
at the end, and it will pause until you press ENTER.
Try this:
static void Main()
    {
    float c, f;
    for (c = -40; c <= 40; c += 5)
        {
        f = 9.0 / 5.0 * c + 32;
        Console.WriteLine("c: {0}; f: {1}", c, f);
        }
    Console.ReadLine();
    }
 
Share this answer
 
v2
Comments
Member 13652359 25-May-18 14:15pm    
The line where the formula is put in, the following error comes up:

Error CS0266 Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)
OriginalGriff 25-May-18 14:25pm    
Brain fart: change
float c, f;
To
double c, f;
Member 13652359 25-May-18 15:27pm    
Thanks for replying and for your help.
OriginalGriff 25-May-18 16:45pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900