我的程序在给出结果之前关闭,年龄差异是错误的。
我检查了所有地方,他们说使用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();
}
}
}
}
另外,如果我在这里犯了一些缩进错误,很抱歉,但实际代码的缩进是正确的。
发布于 2015-05-22 17:16:43
你的问题在这里:
age = Console.Read();
在这里,您只需将年龄设置为输入字符的ASCII码,因为Read
从控制台读取一个符号并返回它的ASCII码。
它应该是相反的
age = Convert.ToInt32(Console.ReadLine());
发布于 2018-06-07 09:10:29
这是我对它的看法。也许不是最好的,但它是有效的:
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;
}
}
}
https://stackoverflow.com/questions/30392762
复制相似问题