gpt4 book ai didi

C#卡路里计数器

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:27 25 4
gpt4 key购买 nike

我是编程的新手,正在学习我的第一门类(class),编程基础知识和我们当前的家庭作业,我有一个我无法解决的问题。

问题是——“一袋 cookies 有 40 block cookies 。袋子上的卡路里信息声称袋子里有 10 份,一份等于 300 卡路里。创建一个应用程序,让用户输入 cookies 的数量他或她实际吃的 cookies ,然后报告消耗的卡路里数。”

我的表格: My form

我在没有调试的情况下运行时得到的错误: The error i get when I run without debugging

//下面是我的代码

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Calorie_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int cookies = int.Parse(textBox1.Text);

int calories = (cookies * 75);

textBox2.Text = calories.ToString();
}
}
}

最佳答案

您在使用 int.Parse() 时遇到此问题方法。此方法只是将您传递给它的任何内容转换为 string。至 int .所以,类似于 "33"将被转换,但是如果您输入的内容显然不是 integer 怎么办?例如 "x"甚至是一个空字符串?

因此,这将被转换为 33 的值在int输入没问题。

int parseResultGood = int.Parse("33");

但这会失败并抛出异常,因为,显然 "x"不能转换成整数。

int parseResultBad = int.Parse("x");

幸运的是,C#为您提供另一种更好地处理此问题的方法,即 int.TryPrase()方法。顾名思义,它尝试解析值,并将其转换为 int。只有在可能的情况下,然后在 out 中将其发回给您参数,同时它会 return true .如果转换失败,比如说,因为您传递了一个非整数值作为 string ,它将return false ,以及 out 的值参数将为 zero .所以根据true/false的返回值您可以知道转换是否成功,并且不会抛出异常。

int tryParseResult = 0;
if (int.TryParse("X", out tryParseResult))
{
// Use the converted value
}
else
{
// Display an error message or something similar
}

不过,我建议你学会调试你的程序。如果你这样做了,你就能自己找出问题所在。评论中链接的文章很棒,请关注。祝你好运!

关于C#卡路里计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58226276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com