这是程序。有人可以告诉我我做错了什么吗?每次我为字符串SolvingFor输入值时,程序都会崩溃。我是编码的新手,所以如果我犯了一个愚蠢的错误,请告诉我。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PercentageCalculator
{
class Program
{
static void Main(string[] args)
{
string SolvingFor;
int part;
int whole;
int percent;
Console.WriteLine("please only use numbers and lowercase letters.");
Console.WriteLine("Are you trying to solve for percent, part, or whole?");
SolvingFor = Convert.ToString(Console.Read());
if (SolvingFor == "part") {
Console.WriteLine("Please Enter Value of the Whole");
whole = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (whole * percent) / 100); }
else if (SolvingFor == "whole")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the Percent");
percent = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / percent);
}
else if (SolvingFor == "percent")
{
Console.WriteLine("Please Enter Value of the part");
part = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please Enter Value of the whole");
whole = Convert.ToInt32(Console.ReadLine()); ;
Console.WriteLine("Your answer is" + (part * 100) / whole);
}
else
{
Console.WriteLine("Please only input valid lowercase letters and numbers. ");
};
Console.Read();
}
}
}
答案 0 :(得分:2)
//SolvingFor = Convert.ToString(Console.Read());
SolvingFor = Convert.ToString(Console.ReadLine());
如果将鼠标悬停在ReadLine上
您将看到它返回一个字符串,因此不需要 Convert.ToString
SolvingFor = Console.ReadLine();
答案 1 :(得分:1)
第一期: 代码下方的一行仅读取一个字符。
使用Console.Read()
代替Console.ReadLine()
,使您可以输入多个字符。
SolvingFor = Convert.ToString(Console.Read());
第二期:
您正在使用Convert.ToInt32(Console.Readline());
请注意,Convert.ToInt32
会在输入提供的数字以外的任何内容上引发异常。
最好使用int.TryParse
来返回转换是否成功。