【问题标题】:C# how to convert data types inside a conditionalC#如何在条件内转换数据类型
【发布时间】:2017-07-13 16:05:08
【问题描述】:

嗨,我做了一个 c# 小程序,向用户请求 2 个数字并返回一个值,但如果用户输入一个双数,程序可以使用 if else 语句解决问题,但我不知道如何做。

这是代码。

using System;

namespace c_
{
class suma
{
    static void Main(string[] args)
    {
        int N1;
        int N2;
        int suma;
        Console.WriteLine ("Digite el numero");
        N1 = int.Parse(Console.ReadLine());
        Console.WriteLine ("Digite el otro numero");
        N2 = int.Parse(Console.ReadLine());
        suma = N1 + N2;
        Console.WriteLine ("Total " + suma); 
    }
}
}

【问题讨论】:

  • 为什么不到处使用double
  • 是的,但我需要做一个 if else 语句,将输入值转换为 double 。
  • 不,您根本不需要 if/else - 只需使用所有 double 值和 double.Parse - 或者可能使用 decimal.Parse 代替,因为 decimal 算术可能不那么令人惊讶...

标签: c# if-statement typeconverter


【解决方案1】:

首先,学习一些基础知识。 Here 您可以阅读有关 Double 的信息。但这是你的解决方案:

        int suma = 0;
        int n = 2;
        for (int i = 0; i < n; i++)
        {
            double number;
            if (!double.TryParse(Console.ReadLine(), out number))
            {
                // Tell user input is invalid
            }
            else
            {
                suma += (int) number;
            }
        }

        Console.WriteLine("Total " + suma);

如果你真的需要告诉用户他的输入类型,那么:

int suma = 0;
int n = 2;
for (int i = 0; i < n; i++)
{
    int intNumber;
    double doubleNumber;
    if (int.TryParse(Console.ReadLine(), out intNumber))
    {
        Console.WriteLine("Digite el numero");
        suma += intNumber;
    }
    else if (double.TryParse(Console.ReadLine(), out doubleNumber))
    {
        Console.WriteLine("Digite el otro numero");
        suma += (int)doubleNumber;
    }
    else
    {
        // Tell user input is invalid
    }
}

Console.WriteLine("Total " + suma);

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 2015-09-27
    • 2018-11-03
    • 2011-05-27
    • 2014-10-09
    • 2013-09-17
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多