【问题标题】:Why are my counter variables not displaying zero? c#为什么我的计数器变量不显示为零? C#
【发布时间】:2017-07-10 12:35:52
【问题描述】:

每次运行此代码时,我的计数变量总是从 48 开始。我将它们明确初始化为 0。我假设这与读取我的 char 变量有关?我是否坚持将输入作为字符串读取并将其转换为字符?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace CountLowers
{
    class Program
    {
        static void Main(string[] args)
        {
            char choice;
            int otherCounter = '0';
            int lowerCounter = '0';

            do
            {
                WriteLine("Enter an Upper or Lower Case Charactor");
                Write("or Enter the '}' key to stop and view results > ");
                choice = Console.ReadKey().KeyChar;

                if (Char.IsLower(choice))
                {
                    WriteLine("\n\n\t" + choice + " is a Lower Case Character\n");
                    lowerCounter = lowerCounter + 1;
                }
                else if (choice != '}')
                {
                    WriteLine("\n\n\tYou did not enter a Lower Case Character\n");
                    otherCounter = otherCounter + 1;
                }            
                else
                {
                    WriteLine("\n\n\tRESULTS\n");
                    WriteLine("You typed in " + lowerCounter + " Lower Case Charactors");
                    WriteLine("\nYou typed in " + otherCounter + " Other Charactors");
                }
            } while (choice != '}');

            Console.ReadKey();
        }
    }
}

【问题讨论】:

  • int otherCounter = '0'; 那将如何编译? c#非常严格,如果确实有错误就不会编译,那就是错误
  • @Beginner 隐式转换从 charint
  • 不管它是否有效......你为什么要这样做?只需使用数字零。
  • 程序编译。我正在使用视觉工作室。

标签: c# loops char


【解决方案1】:

您使用的是零字符'0',而不是整数零。删除单引号。

    int otherCounter = 0;
    int lowerCounter = 0;

【讨论】:

  • 谢谢。我知道我错过了一些简单的事情。我很欣赏积极的解决方案。不知道为什么其他海报不能有帮助。 (不那么粗鲁)
猜你喜欢
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多