试图找出逻辑错误 [英] Trying to figure out the logic Error

查看:60
本文介绍了试图找出逻辑错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以让这个程序给我一个答案,但这是错误的答案。它应该计算一个区域代码的电话费用。任何帮助,将不胜感激。这是我第一次尝试编写数组。



使用System; 
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用System.Threading.Tasks;

命名空间SmithMichaelChatAWhile.cs
{
class Program
{
static void Main(string [] args)
{
int [] areaCodes = {262,414,608,715,815,920};
double [] ratesPerMinute = {0.07,0.10,0.05,0.16,0.24,0.14};

int areaCode;

double cost = 0;
双分钟;

Console.WriteLine(请输入区号);
Console.WriteLine(选择:262,414,608,715,815,920);
areaCode = Convert.ToInt32(Console.ReadLine());
Console.Write(请输入分钟数);
分钟= Convert.ToDouble(Console.ReadLine());

cost = Convert.ToDouble(cost);
cost = ratesPerMinute [0];
Console.WriteLine(此次通话的费用为+费用*分钟);
}

}
}

解决方案

你总是从第一个元素无论您输入什么,所选区域代码实际上始终为262.



使用 Array.IndexOf 找到输入的区号的索引,然后使用该索引获取每分钟的费率。如果用户输入的区号不在列表中,则IndexOf将返回 -1

  int  index = Array.IndexOf(areaCodes,areaCode); 
if (index == -1)
{
Console.WriteLine( 区号无效。);
return ; // 终止Main方法的执行
}
cost = ratesPerMinute [index ];


I can get this program to give me an answer but it is the incorrect answer. It's supposed to calculate the cost of a phone call to a certain area code. Any help would be appreciated. This is my first attempt at writing an array.

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

namespace SmithMichaelChatAWhile.cs
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
            double[] ratesPerMinute = { 0.07, 0.10, 0.05, 0.16, 0.24, 0.14 };

            int areaCode;

            double cost = 0;
            double minutes;

            Console.WriteLine("Please enter an area code ");
            Console.WriteLine("choose between: 262, 414, 608, 715, 815, 920 ");
            areaCode = Convert.ToInt32(Console.ReadLine());
            Console.Write("Please enter number of minutes ");
            minutes = Convert.ToDouble(Console.ReadLine());

            cost = Convert.ToDouble(cost);
            cost = ratesPerMinute [0] ;
            Console.WriteLine("The cost for this call will be " + cost * minutes);
            }
        
    }
}

解决方案

You always take the first element from the array, hence the selected area code will actually always be 262, whatever you input.

Use Array.IndexOf to find the index of the entered area code and then use that index to get the rates per minute. If the user inputted an area code that's not in the list, IndexOf will return -1.

int index = Array.IndexOf(areaCodes, areaCode);
if (index == -1)
{
    Console.WriteLine("Invalid area code.");
    return; // terminate execution of the Main method
}
cost = ratesPerMinute[index];


这篇关于试图找出逻辑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆