【问题标题】:Why is it telling me the sum of 5 numbers is 250 when it's 15?为什么它告诉我 5 个数字的总和是 250 而它是 15?
【发布时间】:2020-07-12 19:52:19
【问题描述】:
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution
{
    static void Main(string[] args)
    {
        int value=0;
        int n = int.Parse(Console.ReadLine());
        string s = Console.ReadLine();

        for(int i = 0;i<=s.Length-1;i++){
            if(s[i]!=0){
                value+=s[i];
                Console.WriteLine(value);
            }
            else{value=0;}
        }

        //Console.WriteLine(value);
    }
}

我觉得我很愚蠢。代码是从字符串中获取5 数字并将它们相加。如果它找到0,那么它将值设置回0,然后再次加起来。但它告诉我12345 的值是250

【问题讨论】:

  • Using the free, built-in Step Debugger 调试代码比您想象的要容易。它还将帮助您了解代码的执行方式,从而帮助您编写更好的代码。
  • 我希望结果是 255。对吗?
  • 那些字符有一个 Unicode 值。您正在对 Unicode 代码点求和。目前尚不清楚n 的用途。这:i &lt;= s.Length - 1 可以重构

标签: c# char


【解决方案1】:

那是因为您要向 int 添加字符:

  • s[i] 不是 int,是 char
  • char '1' 的值作为可以添加到 int 的数值。该值不是 1 而是 48。
  • 您认为您正在执行 1 + 2 + 3 + 4 + 5 但您正在执行 '1' + '2' + '3' + '4' + '5' = 48 + 49 + 50 + 51 + 52 = 250。

你必须这样做

 value+=int.Parse(""+s[i]);

实现你想要的

【讨论】:

    【解决方案2】:

    好吧,你实际上是和chars,而不是ints:

      value+=s[i]; // since s is string, s[i] is of type char
    

    所以你有

    '1' + '2' + '3' + '4' + '5' == // chars
     49 + 50 + 51 + 52 + 53 ==     // corresponding ASCII codes
     255
    

    你应该总结ints;为了将'0' 转换为0,您只需减去0

     string s = Console.ReadLine();
    
     for (int i = 0; i < s.Length; ++i) {
       if (s[i] >= '1' && s[i] <= '9') { // 1..9 numbers only 
         value += s[i] - '0'; // <- Note - '0'
    
         Console.WriteLine(value);
       }
       else 
         value = 0;
     }
    

    【讨论】:

      【解决方案3】:

      s[i] 不是给你一个数字,而是给你一个角色。 += 将累加该字符的 ASCII(或 Unicode)值。看这里:

      Console.WriteLine((int)'1');
      

      这样你将得到 49 + 50 + 51 + 52 + 53,即 255。

      使用int.Parse()将字符串转换为数字:

      value+=int.Parse(""+s[i]);
      

      在程序中你也会看到很多:

      value+=s[i] - '0';
      

      这也有效,因为字符 0 在字符 1 的前面,所以 49 - 48 = 1。

      程序中的第二个错误是

      if(s[i]!=0){
      

      出于同样的原因(字符与数字)应该读作

      if(s[i]!='0'){
      

      n 似乎未使用。您可以删除该行。

      【讨论】:

        猜你喜欢
        • 2010-12-06
        • 2021-03-03
        • 2015-10-11
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多