c#代码中的问题(Noob)
本文关键字:Noob 问题 代码 | 更新日期: 2023-09-27 17:50:31
我的程序在给出结果之前就关闭了,年龄差异是错误的。
我已经检查了所有地方,他们说使用Console.Read()
, Console.ReadLine()
或Console.ReadKey()
,我在他们说之前就这样做了,但它仍然不起作用。有人说用System("PAUSE")
,但这只是给我一个错误。
当我进入21岁时,它还说21 - 12 = 38??
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static String name;
static int age;
static void Main(string[] args)
{
Console.WriteLine("Welcome to the application!");
Console.Write("What's your name? ");
// Setting the name string to the line read from the console.
name = Console.ReadLine();
Console.Write("'n So how old are you " + name + "? ");
// Doing the same thing we did last time with the age.
age = Console.Read();
compareAges();
Console.Read();
}
static void compareAges()
{
if(age < 12)
{
Console.WriteLine("I'm older than you! I'm 12.");
Console.ReadLine();
}
else if(age == 12)
{
Console.WriteLine("We're the same age!!!");
Console.ReadLine();
}
else
{
int ageDifference = age - 12;
Console.WriteLine("You're " + ageDifference + " years older than me!");
Console.ReadLine();
}
}
}
}
注:抱歉,如果我在这里做了一些缩进错误,但实际代码的缩进是正确的
问题出在
age = Console.Read();
好吧,Console.Read()
只读取一个符号 -字符2
在你的例子中是50
int,你有
'2' - 12 == 38 // '2' == 50
补救措施:读取整个字符串,在你的情况下是"21"
String line = Console.ReadLine();
then parse into integer:
// Parse() is the simplest; TryParse() is a better:
// what if a user entered "bla-bla-bla"?
age = int.Parse(line);
你的问题在这里:
age = Console.Read();
这里你只是将age设置为输入字符的ASCII码,因为Read
从控制台读取一个符号并返回它的ASCII码。
应该改成
age = Convert.ToInt32(Console.ReadLine());
以下是我的看法。也许不是最好的,但它是有效的:
using System;
using System.IO;
namespace ConsoleApplication1{
class Program{
public static int Main(){
Program.determineAgeDifference dta = new Program.determineAgeDifference();
string[] input = new string[2];
Console.Write("So, what's your name?'n'n>> ");
input[0] = Console.ReadLine();
Console.Clear();
Console.Write("How old are you?'n'n>> ");
input[1] = Console.ReadLine();
Console.WriteLine(dta(int.Parse(input[1].TrimStart(' ').TrimEnd(' ')));
Console.ReadLine();
return 0;
}
private string determineAgeDifference(int age){
string returnValue = "";
if (age < 12){
returnValue = "I'm older than you. I'm 12!";
}
else if (age == 12){
returnValue = "We are the same age!!!";
}
else{
returnValue = ("You're " + (age - 12).ToString() + "Years older than me!");
}
return returnValue;
}
}
}